Home > Mobile >  In C, why cannot I Realloc memory to a pointer outside of its parent function (the function where it
In C, why cannot I Realloc memory to a pointer outside of its parent function (the function where it

Time:11-16

I built a code in the following manner:

void other_func(int *passed_ptr, int size)
{
    passed_ptr = (int *) realloc(passed_ptr, 15*sizeof(int));   // reallocing to new size
    
    passed_ptr[12] = 34;      //some number as input, this is where program ends abruptly with 'segmentation fault' error

    ....
    ....
}

void parent_func()
{
    int *ptr = malloc(10*sizeof(int));
    other_func(ptr, 10);
    ....
    ....
    ....
}

Why I am not able to realloc the pointer (ptr) outside of its parent function?

CodePudding user response:

C is pass by value

Which means arguments to functions are copied.
If you want to change the value of an int inside a function, you need to pass a int*.
If you want to change the value of aint* inside a function, you need to pass a int**.

See this: Passing by reference in C

CodePudding user response:

The changes you make to passed_ptr inside the function will not be visible outside the function. You need to pass a pointer to the pointer to be able to make changes that are visible to the caller.

Example:

#include <stdbool.h>
#include <stddef.h>

// Both the pointer and the size arguments are here pointers to the variables
// used to call the function:
bool grow_int_arr(int **passed_ptr, size_t *size)
{
    size_t new_size = *size * 15 / 10; // calculate new size

    // don't assign directly to `*passed_ptr` - realloc may fail:
    int *new_ptr = realloc(*passed_ptr, new_size * sizeof *new_ptr);

    if(new_ptr) {               // success, now assign:
        *passed_ptr = new_ptr;
        *size = new_size;
        return true;
    }

    return false;               // realloc failed
}

You could now call the function like so:

void parent_func()
{
    size_t size = 10;
    int *ptr = malloc(size * sizeof *ptr);

    if(ptr) {
        if(grow_int_arr(&ptr, &size)) {   // pass in pointers to the variables
            printf("new size: %zu\n", size);
        } else {
            puts("realloc failed but ptr   size are still valid");
        }
        free(ptr);
    } else {
        puts("malloc failed");
    }
}
  • Related