Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Assigning character to char[x] results in segmentation fault

I have already written a couple of C programs and consider this awkward to ask. But why do I receive a segmentation fault for the following code being supposed to replace "test" by "aaaa"?

#include <stdio.h>

int main(int argc, char* argv[])
{
    char* s = "test\0";
    printf("old: %s \n", s);
    int x = 0;
    while(s[x] != 0)
    {
        s[x++] = 'a'; // segmentation fault here
    }
    printf("new: %s \n", s); // expecting aaaa
    return 0;
}
like image 793
Anonymous Avatar asked Dec 10 '25 20:12

Anonymous


1 Answers

This assignment is writing to a string literal, which is stored in a read-only section of your executable when it is loaded in memory.

Also, note that the \0 in the literal is redundant.

One way to fix this (as suggested in comments) without copying the string: declare your variable as an array:

char s[] = "test";

This will cause the function to allocate at least 5 bytes of space for the string on the stack, which is normally writeable memory.

Also, you should generally declare a pointer to a string literal as const char*. This will cause the compiler to complain if you try to write to it, which is good, since the system loader will often mark the memory it points to as read-only.

like image 103
antron Avatar answered Dec 13 '25 16:12

antron