Łukasz Mleczko Łukasz Mleczko - 1 year ago 90
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

Answer Source

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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download