I'm confused about the usage of malloc and free, here is my example and code:
To be clear, assume we want to read lines from a file and write to a array. The format of the file is:
3
abc
def
ghi
jkl
mno
pqr
I want to store the first three lines into array1, and put the remaining into array2.
The code:
int num;
FILE *fin = fopen("filename", "r");
/*Read the first line of the file*/
fscanf (fin, "%d", &num);
char **array1 = malloc(sizeof(char *) * num);
char **array2 = malloc(sizeof(char *) * num);
/*Apply sizeof(num * num) memory blocks and set the first address to array1[0]*/
array1[0] = malloc(sizeof(char) * num * num);
array2[0] = malloc(sizeof(char) * num * num);
/*Allocate the address of each (char *) array pointer*/
int i;
for (i = 0; i < num-1; i++)
{
array1[i+1] = array1[i] + num;
}
for (i = 0; i < num; i++)
{
fscanf(fin, "%s", array1[i]);
}
The problem arises when calling the free
function:
/*ERROR: free(): invalid next size (fast): 0x0804b318(gdb)*/
free(array1[0]);
free(array1);
Since the address 0x0804b318 is array1[0], I think the memory blocks assigned may not enough. To make it larger:
array1[0] = malloc(sizeof(char) * (num+1) * (num+1));
And it worked, but I'm confused about this, since the first 3 lines of the file are:
abc
def
ghi
The malloc
function returns a pointer to a 3 * 3 char array which is enough to store
the 3 lines, why do we need (3+1) * (3+1)?