混淆访问 malloc 内存(未初始化)

标签 c malloc

声明简单结构:

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/

相关文章:

c - c中printf中的意外换行符

c - 使用指针交换

c - malloc的返回值是虚拟地址还是物理地址?

c - malloc 和 scanf 字符串

c - 如何增加函数参数指向的 block 的大小?

c - malloc 会发生什么?

c - C 中程序的双重释放或损坏 (!prev) 错误

c++ - 如何在 VIsual Studio C++ 2008 中使用本地时间函数

c - c中的open和creat系统调用有什么区别?

c - 如何生成 0 和 max 之间的随机 double 值(在 C 中)?