Confused with accessing malloc memory (Uninitializ

2019-09-08 15:41发布

问题:

Declaring simple struct:

struct s {
    char* addr;
};

s *ips;

Now allocating that struct array memory

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

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

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

回答1:

What will happen will be unpredictable as you can not know what the memory contained. You should either use calloc instead of malloc, or memset the memory after calling malloc.

Personally I prefer to use calloc as it saves a line of code and makes it a little easier to read your code later.



回答2:

Initialize your variables.

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) {

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).



标签: c malloc