Reputation: 1682
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!
Upvotes: 1
Views: 2386
Reputation: 153348
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).
Upvotes: 0
Reputation: 11353
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.
Upvotes: 1