【问题标题】:segmentation fault SIGSEGV dependant on initialisation method分段错误 SIGSEGV 依赖于初始化方法
【发布时间】:2017-06-13 16:29:57
【问题描述】:

我写了一个小函数foo 来改变一个字符串。

当我使用该功能时,有时我会收到 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;
}

【问题讨论】:

  • C 没有字符串类型。而且指针不是数组!
  • @xing, Re "TestString2 指向一个字符串字面量",不,它指向一个字符串。字符串literal 是代表字符串的源代码。

标签: c segmentation-fault


【解决方案1】:

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

TestString1 的大小写是有效的,因为它指向动态分配的内存,您可以更改它。

【讨论】:

    猜你喜欢
    • 2013-07-27
    • 1970-01-01
    • 1970-01-01
    • 2021-10-09
    • 2022-01-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多