4

Original question

Can I use realloc() function like the following code:

int *ptr, i, num=5;

for (i=0; i<num; i++)
  void *nptr = realloc (ptr, (i+1) * sizeof(int) );
synth
  • 65
  • 5
  • 4
    No. Once the original pointer is used in a realloc, only the return value is (hopefully) usable for the next iteration. (and your original pointer isn't initialized; another trip into undefined behavior). It also leaks memory like a sieve. Oddly, initializing `ptr` to NULL would remove the UB, but you would still have the leak. – WhozCraig Jan 19 '14 at 09:47
  • 5
    `ptr` is not initialize. – BLUEPIXY Jan 19 '14 at 09:48

2 Answers2

6

no, you should initialize ptr at the beginning and then assign the new value

int *ptr = 0;

for (unsigned i=0; i<5; i++) {
  void *nptr = realloc (ptr, (i+1) * sizeof(int) );
  if (nptr) ptr = nptr;
  else abort();
}

Otherwise at the first call you could pass some random value to realloc. And the memory that you allocate in subsequent calls would simply be lost.

Jens Gustedt
  • 76,821
  • 6
  • 102
  • 177
-1

No, You should initialize pointer ptr and nptr with NULL. And declare nptr before for loop. your code should be like:

#include<stdio.h>
#include<stdlib.h>
void main()
{
        int *ptr=NULL, i, num=5;
        void *nptr=NULL;
        for (i=0; i<num; i++)
        {
                nptr = realloc (ptr, (i+1) * sizeof(int) );
                if (NULL != nptr)
                    ptr = nptr;
        }
}
Abhitesh khatri
  • 2,911
  • 3
  • 20
  • 29
  • @Abhiteshkhatri In the loop, every time `ptr` is `NULL`. In case that `ptr` is a null pointer, the function behaves like malloc, assigning a new block of size bytes and returning a pointer to its beginning. – BlackMamba Jan 19 '14 at 10:29