R
Robbie Brown
Robbie Brown said:On 26/01/14 13:15, Ben Bacarisse wrote:By the way, you can reduce allocation size mistakes by using the
pattern:
var = malloc(sizeof *var * number_of_elements);
I have valgrind working and it certainly indicates a problem ... but I
don't understand the above (duh!). I think someone else mentioned
something like this before and I didn't get then either (duh! duh!)
var[1] = malloc(sizeof *var[2] * number_of_elements);
The idea is whatever is on the left is written with * in front on the
right, so I'd have put sizeof *var[1] there, myself.
1. I thought malloc returned a pointer
Yes. presumably in my example var is a pointer object. In yours,
var[1] must be a pointer object. sizeof *var[1] is the size of the type
of object pointed to var var[1].
2. If I want an int (32 bits on this machine) why ask for a pointer to
int (64 bits)
I'm baffled! sizeof can be applied to an expression. It does not evaluate the
expression, it just looks to see what type it is and uses that type to
determine the size. See below...
so
int *i = malloc(sizeof(int));
should give me a 64 bit pointer to a 32 bit int
But int *i = malloc(sizeof *i); also works. i is of type 'int *' so *i
is of type 'int'.
Sorry for being so thick, can you elucidate please.
Not knowing stuff is not at all the same as being thick. We all started
off knowing no C at all.
You're very kind
Anyway, I'm pretty sure I see what you mean, I'll do some experimenting
tomorrow, it's been a long day.
BTW valgrind is a wicked bit of kit, cheers for the heads up.
I was convinced my dynamically allocated LinkedList was working, and it
was but I hadn't got the freeing up of memory quite right, there was a
small leak that I was able to fix and an unitialized variable that I
hadn't caught. I would *never* have figured that out at my current level
of knowledge without.