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


I have a structure malloc () 'D, and after using them, I want to free it, but My program stays out here Can anyone tell me what I am doing?

Here's my code:

  structure data {char * filename; Four * size; }; // primarypcs is a long type variable structure data * primary = (structure data *) malloc (primarypcs * sizeof (struct data)); MEMAX (Primary, 0, Size (Structure Data *) * Primarypacks); ... ... ... for (i = 0; i & lt; primarypcs; i ++) {free (primary [i] .philename); // & lt; ---- My program freezes here (primary [size]. Size); // & lt; ---- or here} free (primary);  

Thanks in advance!

Compi

EDIT:

How can I properly memory for file name and size?

EDIT2:

Sorry, but I was in a hurry, and I did not tell you all the information you need. I have to do it now) Smile, I have to make an application, which gets two given drive / folders file list and then compares them. I thought (and still do), the easiest way is, when I keep the filenames and their size in a composition as mentioned above, I have to dynamically allocate memory for file name and size (I Looks like they call it).

You are not presenting the entire code, where many things may be wrong, but one The error is already clear. Line

  memit (primary, 0, size (structure data *) * prefix);  

Not doing what you think is doing this. This is not zeroing the entire array due to type error in sizeof . It was most likely to

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

Note * is not sizeof . Due to this error, most of the points in your array are garbage in the form of their initial values. If you do not set something meaningful in the omitted code, then the call will get garbage logic and will fail if the free .

In general, to minimize the chance of such errors, it is best to mention the type names in your program, except for announcements, since your question has been C ++ (although it is definitely Looks like a C), it is not possible to get rid of the type of code put on malloc , but otherwise I can say that the lower looks better

  structure Data * primary = (structure date *) Malloc (Prathamikpaks * size * Primary); MEMAX (Primary, 0, PrimaryPack * Size * Primary);  

And, as a side note, if your code was intended for C ++, then you can get the same result in a very attractive, compact and portable way < / P>

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

Of course, in this case you have to delete the memory using the appropriate C ++ functionality instead of free .


Comments

Popular posts from this blog

sql - dynamically varied number of conditions in the 'where' statement using LINQ -

asp.net mvc - Dynamically Generated Ajax.BeginForm -

Debug on symbian -