How to free() a malloc()'d structured correctly?

c, free, malloc, pointers

Solution

You are not presenting the entire code, where a lot of things can go wrong, but one error is already obvious. The line

memset( primary, 0, sizeof(struct data *) * primarypcs );   

is not doing what you think it is doing. It is not zeroing the entire array due to type mistake in `sizeof`. It was most likely supposed to be

memset( primary, 0, sizeof(struct data) * primarypcs );   

Note no `*` under `sizeof`. Because of this error, most of the pointers in your array contain garbage as their initial values. If you don't set them to something meaningful in the omitted code, your calls to `free` will receive garbage arguments and fail.

In general, to reduce the chance of such errors it is best to avoid mentioning type names in your program, except in declarations. Since your question is tagged C++ (even though it surely looks like C), it is not possible to get rid of type casts on `malloc`, but otherwise I'd say that the following looks better

struct data *primary = (struct data *) malloc( primarypcs * sizeof *primary );   
memset( primary, 0, primarypcs * sizeof *primary );   

And, as a side note, if your code was intended to be C++, you could get the same result in a much more elegant, compact and portable way

data *primary = new data[primarypcs]();

Of course in this case you'll have to deallocate the memory using the appropriate C++ functionality instead of `free`.

Problem

i have a structure malloc()'d, and after using them, i want to free() it, but my program freezes out here. Can anyone tell me, what i am doing wrong? Here is my code: ``` struct data { char *filename; char *size; }; //primarypcs is a long type variable struct data *primary = (struct data *)malloc( primarypcs * sizeof( struct data ) ); memset( primary, 0, sizeof(struct data *) * primarypcs ); ... ... ... for ( i = 0; i < primarypcs; i++ ) { free( primary[i].filename ); //<----my program freezes here free( primary[i].size ); //<----or here } free( primary ); ``` Thanks in advance! kampi EDIT: How can i correctly malloc memory for filename and size? EDIT2: Sorry, but i was in a hurry, and i didn't told you all the information that you need. Let me do it now :) Basicly, i want create an application, which gets the file list of two given drives/folders and then compares them. I thought (and still do), that the easiest way is, when i store the filenames and their size in a structure like mentioned above. So i have to allocate memory dynamically (i think this what they call it) for filename and size and of corse for the structure too.

Original source

Related problems