0

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?

Brec
  • 87
  • 1
  • 1
  • 8

2 Answers2

4

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.
Gerhardh
  • 11,688
  • 4
  • 17
  • 39
  • Actually, `realloc` at every loop is inefficient. You could keep a separate `size` of `polyNum` and do something like `if (size <= count) {unsigned newsize = 4*size/3+10; polyNums = realloc(polyNums, newsize*sizeof(int)); if (!polyNums) { perror("realloc"); exit(EXIT_FAILURE);}; size = newsize;}` so have some "geometric growth" of your array. – Basile Starynkevitch Dec 03 '16 at 16:11
  • `gets()` without argument (and without prototype) is completely wrong as well. – Jean-François Fabre Dec 03 '16 at 18:38
1

You should take a look at pointers and resource management, more specifically you should learn what deep copy is and how to reallocate dynamic memory.

In general, you should define a temporary pointer for the new larger chunk of memory, copy all the old values to the new memory location and then you can reassign the temporary pointer to the initial pointer, polyNums. Then you are safe to add more new data.


Community
  • 1
  • 1
Ziezi
  • 6,375
  • 3
  • 39
  • 49