c - double free or corruption (faststop) after malloc() call -


i have small program dynamically allocate array of pointer user can enter array of character many time want. created struct flexible array of pointer. problem when try free(arrayptr) , free(arrayptr -> str[i]) malloc call. gives me error double free or corruption (faststop). when take them out. program works fine still don't understand why. happened behind scene? not supposed use free() in case?

#include <stdio.h> #include <stdlib.h> #include <string.h> #include <ctype.h> #include <stdbool.h>    /* num */ char *getnum() {     char *_new, *num, c;      int i;      num =  malloc(sizeof(char));      (i = 0; (c = getchar()) != eof && c != '\n'; i++)     {         _new = realloc(num, + 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 = 0;       struct strholder *arrayptr = malloc(sizeof (struct strholder));        (i = 0; < 6; i++)           arrayptr -> str[i] = malloc(sizeof (arrayptr -> str[i]));        = 0;       while (i < 6) {                  printf("enter %u number: ", + 1);          longnum = getnum();                  arrayptr -> str[i++] = longnum;           }          (i = 0; < 6; i++)          printf("\nnum >> %s\n", arrayptr -> str[i]);         (i = 0; < 6; i++)           free(arrayptr -> str[i]);         free(longnum);      free(arrayptr);       return 0;  } 

you assign pointer getnum() longnum , array element. @ end of function call free() on array elements, including 1 containing pointer got getnum().

so far that's ok, additionally call free(longnum), trying free memory second time. got freed when called free() on corresponding array element.

additionally there memory leak: pointers in array never given free() if overwritten new pointers getnum(). memory reference lost. can avoided calling free(arrayptr -> str[i]) before assigning new pointer returned getnum().


Comments

Popular posts from this blog

java - Static nested class instance -

c# - Bluetooth LE CanUpdate Characteristic property -

JavaScript - Replace variable from string in all occurrences -