【发布时间】:2014-09-07 16:52:14
【问题描述】:
以下代码在测试时输出为
1
0
0
2
0
这很神奇,因为 ptr[3], ptr[4] 没有任何内存分配。尽管他们在其中存储了价值并打印出来。我为 ptr[i] 中的几个较大的 i 尝试了相同的代码,它再次成功编译并给出结果,但是对于非常大的 i 值,大约为 100000,程序会崩溃。如果 calloc() 在单次调用中分配如此大的内存,那么它不值得有效。那么 calloc() 是如何工作的呢?这种差异在哪里?
#include <stdio.h>
void main() {
int * ptr = (int *)calloc(3,sizeof(int));//allocates memory to 3 integer
int i = 0;
*ptr = 1;
*(ptr+3) = 2;//although memory is not allocated but get initialized
for( i =0 ; i<5 ; ++i){
printf("%d\n",*ptr++);
}
}
之后我尝试了这段代码,它连续运行而没有任何输出
#include <stdio.h>
void main() {
int * ptr = (int *)calloc(3,sizeof(int));
int i = 0;
*ptr = 1;
*(ptr+3) = 2;
//free(ptr+2);
for( ; ptr!=NULL ;)
{
//printf("%d\n",*ptr++);
i++;
}
printf("%d",i);
}
【问题讨论】:
-
访问您的进程不拥有的内存是未定义的。有时,它会崩溃。有时,它似乎起作用。任何事情都有可能发生。
-
仅仅因为写入没有崩溃并不意味着
calloc“分配”了该内存。相反,您正在覆盖它没有为您分配的内存并且可能正在用于其他目的。