FreeStyle4 FreeStyle4 - 5 days ago 5
C Question

Malloc within same loop

I have two simple structs which in my main I create with:

struct Car *myCar[200]
struct Car *otherCar[200]


When I first tried to initialize them, I tried:

for (int i = 0; i < 200; i++){
myCar[i] = malloc(sizeof(struct Car*));
otherCar[i] = malloc(sizeof(struct Car*))
}


which doesn't work. but if I split them into separate loops like:

for (int i = 0; i < 200; i++){
myCar[i] = malloc(sizeof(struct Car*));
}

for (int x = 0; x < 200; x++){

otherCar[x] = malloc(sizeof(struct Car*))
}


it works. Could somebody explain to me why it doesn't/does work in each examples?

AnT AnT
Answer

If the target pointer has struct Car * type, then most likely each call to malloc is supposed to allocate enough memory for a single struct Car object. Which means that the size of each memory block you allocate should be sizeof(struct Car), not sizeof(struct Car *) as in your code.

This problem is present in both of your variants, which means that if the second one "works", it is a pure accident.

In general, a good idea would be to stick to the following idiom

for (int i = 0; i < 200; i++){
    myCar[i] = malloc(sizeof *myCar[i]);
    otherCar[i] = malloc(sizeof *otherCar[i]);
}

I.e. just add exactly one * in front of the recipient pointer and use it in sizeof. That way you do not have to count *s and worry about the specific type to use under sizeof.

Comments