tuyen le
tuyen le

Reputation: 315

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

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;

}

Upvotes: 0

Views: 705

Answers (2)

Accountant م
Accountant م

Reputation: 7523

when you did

free(arrayPtr -> str[i]);

you freed a pointer that you have assigned to it another pointer in the line

 arrayPtr -> str[i++] = longNum;

then you freed the same pointer again in line

free(longNum);

Upvotes: 1

sth
sth

Reputation: 229754

You assign the pointer you get from getNum() to longNum and to an array element. At the end of the function you call free() on all the array elements, including the one containing the pointer you got from getNum().

So far that's ok, but you additionally call free(longNum), trying to free that memory a second time. It already got freed when you called free() on the corresponding array element.

Additionally there is a memory leak: The pointers originally in the array are never given to free() if they are overwritten by new pointers from getNum(). So the memory they reference is lost. This can be avoided by calling free(arrayPtr -> str[i]) before assigning the new pointer returned by getNum().

Upvotes: 1

Related Questions