Character assignment to char [x] results in segmentation fault

I've already written a couple of C programs and I find it awkward to ask. But why am I getting a segmentation fault for the following code, which should replace "test" with "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;
}

      

+3


source to share


2 answers


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

Also note that \0

the literal is redundant.

One way to fix this (as suggested in the comments) without copying the string is to 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 usually writeable memory.

In addition, you must declare a pointer to a string literal as const char*

. This will make the compiler complain if you try to write to it, which is good because the bootloader often marks the memory it points to as read-only.

+10


source


Answering the OP's question in a comment posted to @antron.

You need to allocate the character array and then use strcpy()

to initialize it with your text and then overwrite with a

-s.



Allocation can be done statically (i.e. char s[10];

), but make sure there is enough space to store the length of your initialization string (including the terminating one \0

).

Alternatively, you can dynamically allocate memory with malloc()

and free it with free()

. This allows you to allocate enough space to store the initialization string (specify it at runtime with strlen()

).

0


source







All Articles