roufamatic
roufamatic

Reputation: 18485

C newbie malloc question

Why doesn't this print 5?

void writeValue(int* value) {
    value = malloc(sizeof(int));
    *value = 5;
}


int main(int argc, char * argv) {
    int* value = NULL;
    writeValue(value);
    printf("value = %d\n", *value); // error trying to access 0x00000000
}

and how can I modify this so it would work while still using a pointer as an argument to writeValue?

Upvotes: 2

Views: 296

Answers (3)

Yann Ramin
Yann Ramin

Reputation: 33167

Your pointer (int *value) is a value. If you want to keep the above behavior, you need a pointer to a pointer.

void writeValue(int** value) {
    *value = malloc(sizeof(int));
    **value = 5;
}


int main(int argc, char * argv) {
    int *value = NULL;
    writeValue(&value); // Address of the pointer value, creates int**
    printf("value = %d\n", *value); // prints 5
}

Upvotes: 5

kriss
kriss

Reputation: 24157

call malloc before calling writevalue, not inside it (thus you'll get the added benefit to be able to free it).

Your program doesn't print 5, but also has a memory leak by losing address of allocated bloc.

The reason as also explained by others is that the parameter int * value is a copy of int * valuein main. You can think of it as a local variable of the function. You can only access to the place it is pointing to. When you modify value in the function the other value in main is not changed.

void writeValue(int* value) {
    *value = 5;
}


int main(int argc, char * argv) {
    int* value = NULL;
    value = malloc(sizeof(int));
    writeValue(value);
    printf("value = %d\n", *value);
    free(value);
}

Upvotes: 0

KFro
KFro

Reputation: 764

There are 2 bugs, from what I see: 1) If you want to change the value of your pointer you need to pass a pointer to the pointer to your function int **value. 2) If you want to print the value of the pointer in your main, you need to defreference it, *value.

Upvotes: 0

Related Questions