C new malloc question

Why isn't it printed 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 change this to make it work but still use a pointer as an argument for writeValue

?

+2


a source to share


3 answers


A pointer ( int *value

) is a value. If you want to keep the above behavior, you need a pointer to 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
}

      

+5


a source


There are 2 errors from which I can see: 1) If you want to change the value of your pointer, you need to pass a pointer to a pointer to the value of the int ** function. 2) If you want to print the value of the pointer in your master, you need to override it, * value.



0


a source


call malloc before calling writevalue, not inside it (this way you get the added benefit of being able to free it).

Your program doesn't print 5, but it also has a memory leak, losing the address of the allocated block.

The reason, also explained by others, is that the parameter int * value

is a copy int * value

in the main. You can think of this as a local variable to a function. You can only access the location it points to. When you change a value in a function, the other value in main doesn't change.

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

      

0


a source







All Articles