【问题标题】:strsep segmentation faults on different string pointer/array types不同字符串指针/数组类型上的 strsep 分段错误
【发布时间】:2011-04-27 16:55:01
【问题描述】:

平台:Linux、OSX
编译器:GCC

我有一个简单的程序,目前让我感到困惑 - 我知道我正在弄乱几种不同类型的数组/指针来产生这个问题 - 这是故意的 - 我正在努力理解它。

列出的代码将按预期编译和运行,但将调用中的data4 更改为strsep(&data4, "e");data1data3 会导致分段错误。我想知道为什么。

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

int main(int c, char** v) {
    char* data1 = "hello\0";
    char* data2 = strdup(data1);
    size_t sz = strlen(data1);
    char data3[sz+1];
    char* data4;

    memset(data3, 0, sz+1);
    data4 = strncpy(data3, data1, sz);
    data4[sz] = '\0';

    char* found = strsep(&data4, "e");

    if (found == NULL) {
        printf("nothing found\n");
    } else {
        printf("found e\n");
    }

    return 0;
}

【问题讨论】:

    标签: c string memory-management libc


    【解决方案1】:

    在调用 strsep(&data4, "e"); 时改变 data4到 data1 或 data3 会导致分段错误。

    在这种情况下:

    char* found = strsep(&data1, "e");
    

    data1 指向的字符串是字面量,因此无法更改。当strsep() 尝试将“\0”放入其中时,会出现段错误。

    在另一种情况下:

    char* found = strsep(&data3, "e");
    

    data3 是一个数组,而不是一个指针(尽管数组很容易计算为指针,但它们实际上并不是指针),所以 strsep() 无法更新指针的值,这是它一旦找到就会尝试做的事情令牌。我从 gcc 收到以下警告,试图指出这一点:

    test.c:17: warning: passing argument 1 of 'strsep' from incompatible pointer type
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2010-12-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多