不同字符串指针/数组类型上的 strsep 分段错误

发布于 2024-09-28 01:28:04 字数 763 浏览 5 评论 0原文

平台:Linux、OSX
编译器:GCC

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

列出的代码将按预期编译和运行,但将 strsep(&data4, "e"); 调用中的 data4 更改为 data1 code> 或 data3 导致分段错误。我想了解为什么。

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

Platform: Linux, OSX
Compiler: GCC

I've got a simple program which is currently confounding me - I know that I'm messing with a couple different kinds of arrays/pointers to produce this problem - its intentional - I'm trying to understand it.

The code as listed will compile and run as expected, but changing data4 in the call to strsep(&data4, "e"); to data1 or data3 causes a segmentation fault. I would like to understand why.

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

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

呆萌少年 2024-10-05 01:28:04

在调用 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

changing data4 in the call to strsep(&data4, "e"); to data1 or data3 causes a segmentation fault.

In this case:

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

the string pointed to by data1 is a literal so it cannot be changed. When strsep() tries to place a '\0' into it, segfault.

in the other case:

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

data3 is an array, not a pointer (even though arrays easily evaluate to pointers, they are not actually pointers), so strsep() cannot update the value of the pointer which is what it tries to do once it finds the token. I get the following warning from gcc attempting to point this out:

test.c:17: warning: passing argument 1 of 'strsep' from incompatible pointer type
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文