简体   繁体   English

strcmp出现分段错误,但是使用printf打印字符串

[英]Segmentation fault with strcmp, but the string prints using printf

I have a tokenizer method that returns a char** . 我有一个返回char**的tokenizer方法。 The results are being stored in a char** called lineTokens . 结果存储在名为lineTokenschar** When I use printf() to print the first token, I get the correct result, but when I use strcmp(lineTokens[0],"Some text") , I get a seg fault. 当我使用printf()打印第一个标记时,我得到了正确的结果,但是当我使用strcmp(lineTokens[0],"Some text") ,出现了段错误。 The appropriate code is below. 相应的代码如下。

lineTokens = tokenize(tempString);
printf("token[0] = %s\n", lineTokens[0]);
if(strcmp(lineTokens[0], "INPUTVAR")==0){
    printf("It worked\n");
}

EDIT: My tokenize code is as follows 编辑:我的标记化代码如下

char** tokenize(char* input){
int i = 0;
char* tok;
char** ret;
tok = strtok(input, " ");
ret[0] = tok;
while(tok != NULL){
    printf("%s\n", tok);
    ret[i] = tok;
    tok = strtok(NULL, " ");
    i++;
}
ret[i] = NULL;
return ret;

} }

It's impossible to answer this without seeing the code of tokenize() , of course. 当然,如果没有看到tokenize()的代码,就不可能回答这个问题。

My guess is that there is some undefined behavior in that function, which perhaps corrupts the stack, so that when printf() runs and actually uses some more stack space, things go bad. 我的猜测是该函数中存在一些未定义的行为,这可能会破坏堆栈,因此当printf()运行并实际使用更多的堆栈空间时,情况就会变糟。 The thing with undefined behavior is that it's really undefined, anything can happen. 行为不确定的是,它实际上是不确定的,任何事情都可能发生。

Run the code in Valgrind. 在Valgrind中运行代码。

Your tokenize function is broken. 您的标记化功能已损坏。 Every pointer in your code needs to point at allocated memory, which is not the case here. 代码中的每个指针都必须指向分配的内存,在这里情况并非如此。 You get no memory allocated by simply declaring a pointer: a pointer is merely containing an address to memory allocated some place else. 您仅通过声明一个指针就不会分配任何内存:指针仅包含指向分配给其他位置的内存的地址 Given that you set it to point at "some place else", if you don't, it will point at a random garbage address. 假定您将其设置为指向“其他地方”,否则,它将指向随机的垃圾地址。

So you need to rewrite that function from scratch. 因此,您需要从头开始重写该功能。 Either pass a pointer to allocated memory as a parameter or allocate memory dynamically inside the function. 可以将指向已分配内存的指针作为参数传递,也可以在函数内部动态分配内存。 But before you do, I would strongly recommend that you study arrays and pointers some more, for example by reading this chapter of the C FAQ. 但是在您这样做之前,我强烈建议您进一步研究数组和指针,例如通过阅读C FAQ的这一章

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

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