#include <stdio.h>
#include <stdlib.h>
int main()
{
int *a = (int *)malloc(sizeof(int));
// int a[1];
int i;
for(i = 0; i < 876; ++i)
a[i] = i;
printf("%d",a[799]);
}
即使我使用 malloc()
只分配 1 个 int 的空间,为什么这段代码仍然有效?
最佳答案
为什么这段代码有效?即使我使用 malloc 只分配 1 个 int 的空间? 在这种情况下,答案是未定义的行为。
分配 4
字节 block ,例如
int *a = (int *)malloc(sizeof(int)); /* No need to cast the malloc result */
并超越此访问
a[i] = i; /* upto i<1 behavior is guaranteed as only 4byte allocated, not after */
导致未定义的行为,即任何事情都可能发生,你不应该依赖它两次做同样的事情。
旁注,不需要对 malloc()
结果进行类型转换,因为 malloc()
返回类型 void*
及其自动提升安全地进入所需的类型。阅读 Do I cast the result of malloc?
并始终检查返回值malloc()
。例如
int *a = malloc(sizeof(int));
if( a != NULL) {
/* allocated successfully & do_something()_with_malloced_memory() */
}
else {
/* error handling.. malloc failed */
}
关于c - 使用 malloc 的指针时出现奇怪的内存分配,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51080155/