cdynamic-memory-allocationrealloc

Using realloc() to resize an array of integers


I am writing some simple Stack operations with my data structure being an Array.

#define DEFAULT_VAL 10        //in a separate Header file
int *stacky = (int*) malloc (default_size * sizeof(int));

The objective is to write a function to dynamically set the size of the Stack while ensuring that the elements are not lost.

Here is what I have so far:

void Sizer( int size)
{
  #undef DEFAULT_VAL
  #define DEFAULT_VAL size
  maxSize = size;
  int *newbuffer = (int*) realloc (stacky, size);
  if(newbuffer == NULL) //checking if the 'realloc' was successful :)
    {
      printf("PROBLEM HERE :)");              
    }
  else
    {
      stacky = newbuffer;     
    }
}

In my main() function:

int main()
{
  int i;
  for( i=1; i<15; i++) 
   {
     push(i);
   }
  Sizer(9);
  displayStack();
  Sizer(17);
  displayStack();
}

The Output is:

DEFAULT_VAL is now: 9
        9. 9
        8. 8
        7. 7869816
        6. 7877384
        5. 17278
        4. 385207786
        3. 3
        2. 2
        1. 1

DEFAULT_VAL is now: 17
        9. 9
        8. 8
        7. 7869816
        6. 7877384
        5. 17278
        4. 50331651
        3. 3
        2. 2
        1. 1

Any advice is appreciated! Thanks


Solution

  • From the man page:

    The realloc() function changes the size of the memory block pointed to by ptr to size bytes.

    So instead of:

    int *newbuffer = (int*) realloc (stacky, size);
    

    you probably want

    int *newbuffer = (int*) realloc (stacky, size * sizeof(int));
    

    BTW: No need for cast when using malloc and friends. See Do I cast the result of malloc?