2017-06-13 52 views
4

我写了一个小函数foo,它改变了一个字符串。分段错误SIGSEGV依赖于初始化方法

当我使用该函数时,有时会收到一个SIGSEGV错误。这取决于字符串如何初始化。在调用函数main中,通过内存分配初始化字符串并调用strcpy。我可以正确更改该字符串。

另一个字符串(TestString2)在我声明变量时被初始化。我无法修剪这个字符串,但得到了SIGSEGV错误。

这是为什么?

#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; 
} 
+0

C没有字符串类型。而指针不是一个数组! – Olaf

+0

@xing,Re“* TestString2指向字符串*”,不,它指向一个字符串。字符串[文字](https://en.wikipedia.org/wiki/Literal_(computer_programming))是表示字符串的源代码。 – ikegami

回答

6

TestString2的情况下,您将其设置为字符串常量的地址。这些常量不能修改,通常驻留在内存的只读部分。正因为如此,你调用undefined behavior在这种情况下表现为崩溃。

TestString1的情况是有效的,因为它指向允许您更改的动态分配内存。