I have this in an exercise with pointers:
char *str = "Hello";
int count = 0;
int len = 5;
printf("%c\n", *(str + count));
printf("%c\n", *(str + len - count - 1));
*(str + count) = *(str + len - count - 1);
Both *(str + count) and *(str + len - count - 1) are valid values as the printfs attest (I get H and o). So why do I get a bus error when I run the above?
strpoints to a string literal which resides in memory where it is undefined behaviour to write to. Many times the compiler will put these string literals into memory with permissions that do not include write-permissions. This is why you’re crashing.Change it to this:
This will create an array on the stack and initialise it with the C-string
"Hello"; since it resides on the stack, you can freely modify it.