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
?
a source to share
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
}
a source to share
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);
}
a source to share