与访问malloc内存混淆(未初始化) [英] Confused with accessing malloc memory (Uninitialized)

查看:117
本文介绍了与访问malloc内存混淆(未初始化)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

声明简单的结构:

struct s {
    char* addr;
};

s *ips;

现在分配该结构数组内存

Now allocating that struct array memory

num = 5
ips = (r *) malloc(num * sizeof(r));

我知道malloc只是分配内存,并且不初始化,可能会有垃圾值.

I know malloc just allocates memory, and don't initialize, there could be garbage values.

现在我想知道是否不初始化一个,然后尝试访问会发生什么?

Now I wonder if I don't initialize one, and try to access what would happen?

//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);
}

理想不应进入此for循环.但是后来我认为可能是因为垃圾价值.我不确定!

Ideal should not be going into this for loop. But then I think because of garbage value it may be. I'm not sure!

推荐答案

初始化变量.

不进行初始化-所有投注均关闭.
知道ips[4].addr未初始化.因此使用:

Without initialization - all bets are off.
ips[4].addr, as you know, is uninitialized. So using:

// Various code
...
if(ips[4].addr) {

是一种简单的询问以下内容的复杂方法吗?

is a convoluted way of simple asking what does the following do?

int i;
if (i) {

每次运行程序时,i的值都可以相同.如果可能不同.没有理想的情况发生.这是简单的未定义行为(UB).

The value of i could be the same every time you run the program. If could be different. There is no ideal of what should happen. It is simple undefined behavior (UB).

这篇关于与访问malloc内存混淆(未初始化)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆