From: James on
Hi Guys,

my understanding is that each call to malloc should have a corresponding
free. However, can somebody please point out what I'm doing wrong in the
below code that causes my freeing of memory to result in the Visual C++ heap
corruption errors?

Below is the function that I have written:

void TestMultiDim()
{
char** mArray;
int rows = 50;
char* p;
char* q;
int i;
char* data = "John Doe";
size_t len;
len = rows * sizeof(char*);
mArray = (char **)malloc(len);
if(mArray == NULL)
{
exit(EXIT_FAILURE);
}

//Create the sub arrays
//for(p = mArray; *p!='\0'; p++)
for(i = 0; i < rows; i++)
{
//*p = (char*)malloc(len);
mArray[i] = (char*)malloc(len);
//if(*p == NULL)
if(mArray[i] == NULL)
{
exit(EXIT_FAILURE);
}
//memset(*p, 0, len);
}

//Populate Data
//for(p = mArray; *p !='\0'; p++)
for(i = 0; i < rows; i++)
{
mArray[i] = data;
//*p = data;
}

//Print out List
//for(p = mArray; *p !='\0'; p++)
for(i = 0; i < rows; i++)
{
printf("%s\n", mArray[i]);
}


//Clean Up:
for(i = 0; i < rows; i++)
{
free(mArray[i]);
mArray[i] = NULL;
}
free(mArray);

}


From: Hugh Moran on


"James" wrote:

> Hi Guys,
>
> my understanding is that each call to malloc should have a corresponding
> free. However, can somebody please point out what I'm doing wrong in the
> below code that causes my freeing of memory to result in the Visual C++ heap
> corruption errors?
>
> Below is the function that I have written:
>
> void TestMultiDim()
> {
> char** mArray;
> int rows = 50;
> char* p;
> char* q;
> int i;
> char* data = "John Doe";
> size_t len;
> len = rows * sizeof(char*);
> mArray = (char **)malloc(len);
> if(mArray == NULL)
> {
> exit(EXIT_FAILURE);
> }
>
> //Create the sub arrays
> //for(p = mArray; *p!='\0'; p++)
> for(i = 0; i < rows; i++)
> {
> //*p = (char*)malloc(len);
> mArray[i] = (char*)malloc(len);
> //if(*p == NULL)
> if(mArray[i] == NULL)
> {
> exit(EXIT_FAILURE);
> }
> //memset(*p, 0, len);
> }
>
> //Populate Data
> //for(p = mArray; *p !='\0'; p++)
> for(i = 0; i < rows; i++)
> {
> mArray[i] = data;
> //*p = data;
> }
>
> //Print out List
> //for(p = mArray; *p !='\0'; p++)
> for(i = 0; i < rows; i++)
> {
> printf("%s\n", mArray[i]);
> }
>
>
> //Clean Up:
> for(i = 0; i < rows; i++)
> {
> free(mArray[i]);
> mArray[i] = NULL;
> }
> free(mArray);
>
> }
>
>
>
Hi

This isnt the most readable code, but at first glance it seems you are
eventually freeing a pointer that actually points to the text "Jonn Doe". The
memory that contains the data "John Doe" was never allocated using malloc, it
pre-existed (part of the programs static storage area).

I suspect this is why the free fails.

Hugh Moran
http://www.morantex.com