Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why I've allocated a pointer memory in a function, but it's also NULL?

Tags:

c

The code confused me.

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

void create_int(int *p)
{
    p = (int *) malloc(sizeof(int));
}

int main()
{
    int *p = NULL;

    create_int(p);

    assert(p != NULL);  /* failed. why? I've allocated memory for it. */

    return 0;
}
like image 750
HiMing Avatar asked May 08 '26 22:05

HiMing


2 Answers

You are not passing the pointer value back from the function. Try:

void create_int(int **p) {
     *p = (int *) malloc(sizeof(int)); 
}  

int main() {
     int *p = NULL;      
     create_int(&p);
     assert(p != NULL);  /* failed. why? I've allocated memory for it. */
     return 0;
} 
like image 152
Ken Keenan Avatar answered May 11 '26 12:05

Ken Keenan


The variable p in the function create_int is a copy of the variable p in main. So any changes made to p in the called function does not get reflected in main.

To make the change get reflected in main you need to either:

Return the changed value:

int* create_int(int *p) {
    p = malloc(sizeof(int));
    // err checking
    return p:
}
...
// in main:
p = create_int(p);

Or pass the address of p as:

void create_int(int **p) {
    *p = malloc(sizeof(int));
    // err checking
}
...
// in main:
create_int(&p);
like image 43
codaddict Avatar answered May 11 '26 12:05

codaddict