I have a 2D array like so:
char * array[2][2];
I wanted it to store char *
, so I tried to malloc()
using:
for(i=0:i<2;i++){
for(j=0:j<2;j++)
{
array[i][j]=(char*)malloc(sizeof(char *)*2);
}
}
After that, I stored some elements of char *
in the 2D array, and the 2D array can print them out, which is fine.
I then tried to deallocate my 2D array using:
for(i=0:i<2;i++){
for(j=0:j<2;j++){
free(array[i][j]);
}
}
When I run the program, I get a "free() : invalid pointer" message.
I tried using Valgrind, which reports that all my allocs and frees are accounted for. However it shows that I've "definitely lost" some bytes.
Any views or thoughts will help.
Here's a sample code to demonstrate what I'm talking about:
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
int main()
{
char * r0c0 = " hello ";
char * r0c1 = " bye ";
char * r1c0 = " this ";
char * r1c1 = " is me ";
int i=0;
int j=0;
for(i=0;i<2; i++)
{
for(j=0;j<2;j++)
{
*(*(array+i)+j) = (char *)malloc(sizeof(char *)*2);
}
}
array[0][0]= r0c0;
array[0][1]= r0c1;
array[1][0]= r1c0;
array[1][1]= r1c1;
for(i=0;i<2;i++)
{
for(j=0;j<2;j++)
{
printf("%s\t",array[i][j]);
}
printf("\n");
}
for(i=0;i<2; i++)
{
for(j=1;j>=0;j--)
{
free(*(*(array+i)+j));
}
}
return EXIT_SUCCESS;
}