2017-06-13 70 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的情況是有效的,因爲它指向允許您更改的動態分配內存。