尝试释放 C 中的内存时出现堆损坏错误
我有这段代码:
#include <stdio.h>
#include<stdlib.h>
int* create_arr(int start, int end) {
int length = end - start, i = start, j;
int* arr;
arr = (int*)malloc(sizeof(int) * length);
if (arr == NULL) {
printf("memory allocation problem");
exit(1);
}
for (j=0; i <= end; i++, j++) {
arr[j] = i;
}
return arr;
}
void main() {
int num, num2;
int *arr;
scanf_s("%d %d", &num, &num2);
arr = create_arr(num, num2);
for (int i = 0; i <= num2 - num; i++) {
printf("%d, ", arr[i]);
}
free(arr);
}
对于这段代码,我分配内存并将值设置到其中的部分工作正常,但是当我添加最后一行时:
free(arr);
它会弹出一条错误消息,内容如下: “调试错误,检测到堆损坏” 我想知道释放内存时我做错了什么,并且希望得到一些帮助。
i have this code:
#include <stdio.h>
#include<stdlib.h>
int* create_arr(int start, int end) {
int length = end - start, i = start, j;
int* arr;
arr = (int*)malloc(sizeof(int) * length);
if (arr == NULL) {
printf("memory allocation problem");
exit(1);
}
for (j=0; i <= end; i++, j++) {
arr[j] = i;
}
return arr;
}
void main() {
int num, num2;
int *arr;
scanf_s("%d %d", &num, &num2);
arr = create_arr(num, num2);
for (int i = 0; i <= num2 - num; i++) {
printf("%d, ", arr[i]);
}
free(arr);
}
for this code the part where i allocate the memory and set values into it works fine but when i add the very last line:
free(arr);
it makes an error message popup that says:
"debug error, heap corruption detected"
im wondering what im doing wrong when freeing the memory and would love some help on this.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
这个 for 循环
是不正确的,因为根据变量
length
的值,数组具有结束 - 开始元素。循环中的条件应为
j <<长度
或i <结束
。或者您需要将
length
的值增加一。一般来说,编写的循环会让代码的读者感到困惑。
您可以改为编写
此 for 循环中的条件
i <= num2 - num
也是不正确的,原因与上面指出的循环相同。必须是
您应该在函数内检查参数
end
的值至少不小于参数start
的值。如果动态分配的数组必须包含[start, end]
范围内的值,则内存分配应类似于该函数可以通过以下方式之一定义,前提是该范围必须包括
start
和end
的值。或者
注意,根据 C 标准,不带参数的函数 main 应声明为
This for loop
is incorrect because the array has end - start elements according to the value of the variable
length
The condition in the loop shall be either
j < length
ori < end
.Or you need increase the value of
length
by one.In general the loop as written confuses readers of the code.
You could write instead
Also the condition
i <= num2 - num
in this for loopis incorrect by the same reason as the loop pointed to above. It must be
You should check within the function that the value of the parameter
end
at least is not less than the value of the parameterstart
. And if the dynamically allocated array must contain values in the range[start, end]
inclusively then the memory allocation should look likeThe function can be defined in one of the following ways provided that the range must include the both values of
start
andend
.or
Pay attention to that according to the C Standard the function main without parameters shall be declared like