简体   繁体   中英

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 ?

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
}

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.

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 * value in 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);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM