Łukasz Mleczko Łukasz Mleczko - 20 days ago 4
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';
return str;

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

Online Compiler: LINK


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.