I have a small program to dynamically allocate array of pointer so user can enter an array of character as many time as they want. I created a struct with flexible array of pointer. The problem is when I try to free(arrayPtr)
and free(arrayPtr -> str[i])
from malloc
call. It gives me the error double free or corruption (faststop). But when I take them out. The program works fine but I still don't understand why. What happened behind the scene? Am I not supposed to use free()
in this case?
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
#include <stdbool.h>
/* Get num */
char *getNum()
{
char *_new, *num, c;
int i;
num = malloc(sizeof(char));
for (i = 0; (c = getchar()) != EOF && c != '\n'; i++)
{
_new = realloc(num, i + 2);
num = _new;
num[i] = c;
}
if (c == '\n')
num[i] = '\0';
num[i] = '\0';
return num;
}
struct strHolder {
int size;
char *str[];
};
// Main
int main()
{
char *longNum;
unsigned i = 0;
struct strHolder *arrayPtr = malloc(sizeof (struct strHolder));
for (i = 0; i < 6; i++)
arrayPtr -> str[i] = malloc(sizeof (arrayPtr -> str[i]));
i = 0;
while (i < 6) {
printf("Enter %u number: ", i + 1);
longNum = getNum();
arrayPtr -> str[i++] = longNum;
}
for (i = 0; i < 6; i++)
printf("\nnum is >> %s\n", arrayPtr -> str[i]);
for (i = 0; i < 6; i++)
free(arrayPtr -> str[i]);
free(longNum);
free(arrayPtr);
return 0;
}