我是 C 初学者。我想知道 malloc
是如何工作的。
这是一个示例代码,我在尝试理解它的工作原理时编写的。
代码:
#include<stdio.h>
#include<stdlib.h>
int main() {
int i;
int *array = malloc(sizeof *array);
for (i = 0; i < 5; i++) {
array[i] = i+1;
}
printf("\nArray is: \n");
for (i = 0; i < 5; i++) {
printf("%d ", array[i]);
}
free(array);
return 0;
}
输出:
Array is:
1 2 3 4 5
在上面的程序中,我只为 1 个元素分配了空间,但数组现在包含 5 个元素。那么既然程序运行顺利,没有任何错误,那么realloc()
的用途是什么呢?
谁能解释一下为什么吗?
提前致谢。
最佳答案
程序运行顺利并不意味着它是正确的!
尝试将 for 循环中的 5
增加到一定程度(例如,500000
就足够了)。在某些时候,它会停止工作,并给您一个 SEGFAULT
。
这称为未定义行为。
valgrind
还会警告您有关此问题的信息,如下所示。
==16812== Invalid write of size 4
==16812== at 0x40065E: main (test.cpp:27)
如果您不知道
valgrind
是什么,请查看:How do I use valgrind to find memory leaks? 。 (顺便说一句,这是一个很棒的工具)这应该有助于为您提供更多说明:Accessing unallocated memory C++
关于c - C 中 malloc 的工作原理,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44985721/