views:

110

answers:

3

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?

+5  A: 

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
}
Yann Ramin
I believe you should still allocate an `int`, not a pointer. Although `sizeof(int*) == sizeof(int)` on a lot of platforms, but still...
Péter Török
My mistake, fixed.
Yann Ramin
Hey, is Kriss's point valid -- that is, can I `free` the memory if it's `malloc`'d in the function?
roufamatic
@roufamatic: Yes, you can free() that memory from anywhere. However, never attempt to free() something more than once. Also, do not free() then access memory.
Yann Ramin
A: 

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.

KFro
A: 

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);
}
kriss