char* foo = (char*) malloc(sizeof(char)*50); foo = "testing";
In C, i can see the first character of that string :
printf("%c",foo[0]);
But when i try to change that value :
foo[0]='f'
It gives error in runtime.
How can i change this, dynamically allocated, char array’s values?
You are setting foo to point to the string literal (
"testing") not the memory you allocated. Thus you are trying to change the read only memory of the constant, not the allocated memory.This is the correct code:
or even better
to protect against buffer over-run vulnerability.