Hello,

I have a quick question about malloc. If I create a loop where I'm allocating memory to a pointer character array. To which each array gains the same amount of memory allocation. Do I have to free each one of those arrays with in the variable? Or is it efficient enough to simply free the variable it self?

//my loop example
for(for_loop_conditions)
{
    charArray[i] = (char*)malloc(size);
}
//Do I do this?
for(for_loop_conditions)
{
   free(charArray[i]);
}

//or
free(charArray);

thanks,
-A2H

// First you have to do this
for(for_loop_conditions)
{
   free(charArray[i]);
}

// ... and then also this
free(charArray);

So there has to be a matching free() for each malloc() that you do.

PS. Just to be clear ... if charArray is also dynamically allocated, it needs to be declared as: char ** charArray i.e. not char *charArray .

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.