realloc

Hi there!

I have seen some examples of realloc. Most of them use two pointers, the first one to be passed as a parameter to realloc an the second one to save the return of realloc. Then the first pointer is assigned to the second pointer. Here is an example (http://www.cplusplus.com/reference/cstdlib/realloc/)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
int input, n;
int* numbers = NULL;
int* more_numbers = NULL;
do {
     printf ("Enter an integer value (0 to end): ");
     scanf ("%d", &input);
     count++;

     more_numbers = (int*) realloc (numbers, count * sizeof(int));

     if (more_numbers!=NULL) {
       numbers=more_numbers;
       numbers[count-1]=input;
     }
     else {
       free (numbers);
       puts ("Error (re)allocating memory");
       exit (1);
     }
  } while (input!=0);


My question: Is there any problem to use only one pointer?? This code works well for me:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25

int input, n;
    int count = 0;
    int* numbers = NULL;

    do
    {
        printf("Enter an integer value (0 to end): ");
        scanf("%d", &input);
        count++;

        numbers = (int*) realloc(numbers, count * sizeof (int));

        if (numbers != NULL)
        {
            numbers[count - 1] = input;
        }
        else
        {
            free(numbers);
            puts("Error (re)allocating memory");
            exit(1);
        }
    }
    while (input != 0);


Or is it considered a bad practice?

Thank you very much in advance!

> Is there any problem to use only one pointer?

If there is not enough memory, the old memory block is not freed and null pointer is returned.
http://en.cppreference.com/w/cpp/memory/c/realloc

If the pointer is the only pointer pointing to previously allocated memory, there would be a leak if realloc() fails.
Topic archived. No new replies allowed.