声明简单结构:
struct s {
char* addr;
};
s *ips;
现在分配那个结构数组内存
num = 5
ips = (r *) malloc(num * sizeof(r));
我知道 malloc 只是分配内存,并没有初始化,可能会有垃圾值。
现在想知道如果不初始化一个,尝试访问会怎么样?
//Init for 4 of them
for(int i = 0; i < num-1; i++)
ips[i].addr = strdup("123");
//Accessing un-initialize one:
if(ips[4].addr) {
printf("Accessing uninitialize one and lets say freeing!!!");
free(ips[4].addr);
}
Ideal 不应该进入这个 for 循环。但后来我认为可能是因为垃圾值(value)。我不确定!
最佳答案
会发生什么是不可预测的,因为你无法知道内存中包含什么。您应该使用 calloc
而不是 malloc
,或者在调用 malloc
之后使用 memset
内存。
就我个人而言,我更喜欢使用 calloc
,因为它可以节省一行代码,并且让您以后更容易阅读您的代码。
关于混淆访问 malloc 内存(未初始化),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17687182/