简体   繁体   English

strsep() 导致段错误 - 为什么?

[英]strsep() causes segfault - why?

I am a little bit confused about pointer-of-pointer-const-var-string-char;) Her's my code:我对pointer-of-pointer-const-var-string-char有点困惑;)她是我的代码:

char* str_get_var(char *string,char delim)
{
        char    *found,
                *found2,
                *teststring;

printf("var string: %s\t",string);
teststring=strdup(string);
printf(" ---- var teststring: %s\n",teststring);

string=strdup(teststring);

found = strsep(&teststring,&delim);
printf("teststring \t var found: %s\n",found);
found2 = strsep(&string,&delim);
printf("string \t\t var found2: %s\n",found2);

return found;
}


int main(int argc, char *argv[])
{
char *message;
char trenner;
char *gefun;

message="ehzg=1";
trenner = '=';

printf("Start\n");
gefun=str_get_var(message,trenner);
printf("Ende\n");
return(0);
}

The programm produces the following output:该程序产生以下 output:

Start
var string: ehzg=1       ---- var teststring: ehzg=1
teststring       var found: ehzg
string           var found2: ehzg
Ende

As you might see from the code I would say the strdup to teststring is not needed as I would expect I can use the *string directly.正如您从代码中看到的那样,我会说不需要到 teststring 的strdup ,因为我希望我可以直接使用*string However, as soon as I comment the following line I am getting a SegFault:但是,只要我评论以下行,我就会收到 SegFault:

\\string=strdup(teststring);

Her's the output when commented out:注释掉时,她是 output:

Start
var string: ehzg=1       ---- var teststring: ehzg=1
teststring       var found: ehzg
Speicherzugriffsfehler

So my question(s): How can I use *string directly for strsep?所以我的问题是:如何直接将*string用于 strsep? Why do I get a segfault when not doing strdup with the same content?为什么不使用相同内容执行strdup时会出现段错误?

(BTW: Coding on Raspbian, if important). (顺便说一句:在 Raspbian 上编码,如果重要的话)。

Thanks!谢谢! /knebb /knebb

strchr could be used to find an = in the literal string. strchr可用于在文字字符串中查找=

#include <stdio.h>
#include <string.h>
char* str_get_var(char *string,char delim)
{
    char    *found2 = NULL;

    printf("var string: %s\t",string);

    found2 = strchr ( string, delim);
    if ( NULL != found2) {
        printf ( "string \t\t var found2: %s\n", found2);
    }

    return found2;
}

int main(int argc, char *argv[])
{
    char *message = "ehzg=1";
    char trenner = '=';
    char *gefun = NULL;

    printf ( "Start\n");
    gefun = str_get_var ( message, trenner);
    printf ( "Ende\n");
    if ( NULL != gefun) {
        printf ( "%.*s\n", (int)( gefun - message), message);
        printf ( "%s\n", gefun);
    }
    return(0);
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM