I am trying to reduce the size of a char **
double pointer using realloc
.
First the char **
pointer is allocated using malloc
and then the individual char*
pointers as given below.
char **first= (char**)malloc(num*sizeof(char*));
char **last=(char**)malloc(num*sizeof(char*));
for(int i=0;i<num;i++)
{
//each individual pointer holds 20 characters
first[i]=(char*)malloc(20*sizeof(char));
last[i]=(char*)malloc(20*sizeof(char));
}
Now after some operations, I want to reduce the size of first and last by one counter value where counter is less than num
.
Purpose is to free last counter number of records.
If I do the following
//Freeing up internal pointer memories
i = 0;
while (i<counter)
{
free(first[num1-1 - i]);
free(last[num1-1-i]);
i++;
}
//Reducing the size of the double pointer using realloc
first = (char **)realloc(first, (num1-counter) * sizeof(char *));
last = (char **)realloc(last, (num1-counter) * sizeof(char *) );
After this if I print the records
for(i=0; i<num - counter; i++){
printf("First Name: %s ",first[i]);
printf("Last Name: %s ",last[i]);
}`
The last record seems to be corrupted.
If I just perform the following and do not free the individual char *
pointers, it works fine.
first = (char **)realloc(first, (num1-counter) * sizeof(char *));
last = (char **)realloc(last, (num1-counter) * sizeof(char *) );
My question is does realloc
of a double pointer to reduce the size, internally frees up the internal pointers and as I am doing both, it is some how corrupting the memory?