SIGSEGV segmentation error depends on initialization method

I wrote a small function foothat changes the line.

When I use this function, sometimes I get a SIGSEGV error. It depends on how the string is initialized. In the calling function, the mainstring is initialized by allocating memory and calling strcpy. I can change this line correctly.

The other line ( TestString2) is initialized when I declare this variable. I cannot trim this line, but get a SIGSEGV-fault.

Why is this?

#include <stdio.h>
#include <stdlib.h>
#include <string.h>



void foo(char *Expr)
{
    *Expr = 'a';
}



int main()
{
    char  *TestString1;
    char  *TestString2 = "test   ";

    TestString1 = malloc (sizeof(char) * 100);
    strcpy(TestString1, "test   ");

    foo(TestString1);
    foo(TestString2);

    return 0;
}
+4
source share
1 answer

TestString2 . . - undefined , .

TestString1 , , .

+6

Source: https://habr.com/ru/post/1679168/


All Articles