Search code examples
cfunctionpointersmallocrealloc

C - realloc not reflecting back to main


I am currently learning how dynamic memory management is working, more specifically realloc and how it is done in functions.

In following program I just wanted to try to allocate some numbers in function a() using malloc and then pass them to another function b(). In b() I pass the address of the pointer to c() in order to realloc the memory twice the size and initialise it with numbers.

Now coming to my question: why does the output in function b() show the correct numbers, but in the main function it does not? Shouldn't the pointer "numbers" in main also be pointing to the reallocated memory?

Thanks in advance.

Code:

#include <stdlib.h>
#include <stdio.h>

#define SIZE 3

int a(int **numbers);
int b(int *numbers);
int c(int **numbers);

int main()
{
  int *numbers = NULL;

  a(&numbers);

  for(size_t i = 0; i < 2 * SIZE; i++)
    printf("In main after a: %i\n", numbers[i]);

  b(numbers);

  for(size_t i = 0; i <  2 * SIZE; i++)
    printf("In main after b: %i\n", numbers[i]);

  return 0;
}

int a(int **numbers)
{
  *numbers = malloc(SIZE * sizeof(numbers));
  if(!numbers)
  {
    free(numbers);
    return -1;
  }


  for(size_t i = 0; i < SIZE; i++)
    (*numbers)[i] = i;

  return 0;
}

int b(int *numbers)
{
  c(&numbers);

  for(size_t i = 0; i < 2 * SIZE; i++)
    printf("In b after c: %i\n", numbers[i]);

  return 0;
}

int c(int **numbers)
{
  int *n_new = realloc(*numbers, 2 * SIZE * sizeof(numbers));
  if(!n_new)
  {
    free(n_new);
    return -1;
  }

  for(size_t i = 0; i < 2 * SIZE; i++)
    n_new[i] = i * 2;

  *numbers = n_new;

  return 0;
}

Output:

In main after a: 0
In main after a: 1
In main after a: 2
In main after a: 0
In main after a: 0
In main after a: 0
In b after c: 0
In b after c: 2
In b after c: 4
In b after c: 6
In b after c: 8
In b after c: 10
In main after b: 0
In main after b: 0
In main after b: 2
In main after b: 0
In main after b: 0
In main after b: 0

Solution

  • You need to pass the pointer by pointer to b() as well. As it stands, calling b(pointer) cannot modify pointer in main(). Do it the same way you call a(&pointer) instead.

    Also, do not bother to call free() on pointers you know are null (when malloc has failed). It doesn't do anything.