Łukasz Mleczko Łukasz Mleczko - 2 months ago 6
C Question

Operation on pointers in c

Why this code won't work, on online compiler return segment fault, on my linux VPS memory leak...

#include <ctype.h>
#include <stdio.h>
#include <string.h>
char *a_foo(char *str) {
unsigned char *p = (unsigned char *)str;

while (*p) {
*p = 'a';
p++;
}
return str;
}

int main() {
char * test = "TestTest";
a_foo(test);
printf("result: %s\n", test);
}


Online Compiler: LINK

Answer

The string literal "TestTest" is probably stored in read-only memory in your environment, so the code in a_foo that attempts to write to it would fail.

The type of a string literal is const char * and the compiler should warn you if you try to assign it to a non-const pointer variable.