Search code examples
cdynamic-memory-allocation

C programming, losing data after realloc


I am trying to get string of numbers and put it inside an int array. I have no idea how many numbers I am going to get so I need to use dynamic allocation.

I created an array by using malloc and tried to resize it by +1 every time inside the loop.

This is my code

void main() 
{

    char *s;
    int *polyNums;
    int count = 0;
    char *token;  
    s = gets();
    polyNums = (int *)malloc(sizeof(int));
    if (polyNums == NULL)
    {
        printf("Could not allocate required memory\n");
        exit(1);
    }
    token = strtok(s, " ");
    while (token != NULL)
    {
        polyNums[count] = *token - '0';
        count++;
        polyNums = realloc(polyNums, count+1);
        token = strtok(NULL, " ");
    }

}

My problem is that every time it's doing realloc, all the saved numbers are gone, if my string is "1 2 3" so in loop 1 the polyNums[0] is 1, but I am loosing it in loop 2 after reallocating. Can some one please tell me where I went wrong?


Solution

  • You do not allocate enough memory for your array.

    int *polyNums;   // Holding integer!
    int count = 0;
    polyNums = (int *)malloc(sizeof(int)); // enough space for interger. OK!
    ...
    while(...)
    {
      polyNums[count] = *token - '0';
      count++;
      polyNums = realloc(polyNums, count+1);  // Not enough space for intergers!
      ...
    }
    

    You access an array holding int values but you only allocate 1 byte per element. While your first allocation can hold the first integer, you allocate less memory for any forther number.

    polyNums = realloc(polyNums, (count+1)*sizeof(*polyNums));
    

    Aside from that:

    • Do not cast the return value of malloc
    • Do not assign the return value of realloc directly to your pointer. In case of NULL return value you lose your old data.