简体   繁体   English

从C函数以char *返回的打印字符串

[英]Printing string returned as a char* from a C function

I'm writing a simple shell program in C. As part of the program, I'm writing a tokenizer to break up user input into tokens. 我正在用C语言编写一个简单的Shell程序。作为该程序的一部分,我正在编写一个令牌生成器,以将用户输入分解为令牌。 Each time the tokenizer is called, it returns the next token. 每次调用令牌生成器时,它都会返回下一个令牌。 The code for the tokenizer looks like this: 令牌生成器的代码如下所示:

char* nextToken(char string[])
{
char token[50]= {}; //stores the current token
//More code here, will post if necessary
puts(token);
return token;
}

int main()
{
char inputString[] = "cpgm one two <three| script a b >file";
char *token = nextToken(inputString);
while(*token!='\0') //I'm using a char[] with a single null character as a delimiter to indicate the last token has been reached
{
    token = nextToken(inputString);
}

}

When I run the program like this, the "puts" works properly; 当我这样运行程序时,“ puts”工作正常; that is to say, each time the function is called, the appropriate token is printed in the correct order, like this: 也就是说,每次调用该函数时,都会以正确的顺序打印适当的令牌,如下所示:

cpgm one two < three | cpgm一二<三| script ab > file 脚本ab>文件

However, when I remove the "puts" line in nextToken and put it in the main function, like this: 但是,当我删除nextToken中的“ puts”行并将其放在main函数中时,如下所示:

 while(*token!='\0')
 {
     puts(token);
     token = nextToken(inputString);
 }

and try to print the token from my main function instead, all I see is a list of weird characters, like this: 然后尝试从我的主函数中打印令牌,我看到的只是一个奇怪的字符列表,如下所示:

bHd? BHD? bH bH bHd bHd? bH bh bHd bHd?

bHd? bHd?

Any idea why this is happening? 知道为什么会这样吗?

Thanks. 谢谢。

You are allocating your string token on the stack. 您正在堆栈上分配字符串token This means that when you return it, it will be deallocated, and can't be used any more. 这意味着当您返回它时,它将被释放,并且不能再使用了。 You should allocate memory for your string instead: 您应该为字符串分配内存:

char *token = malloc(50);

You also then have to remember to free the string later, once you're done with it, by calling 然后,您还必须记住,一旦完成处理,就可以通过调用以下命令来释放该字符串

free(token);

It's because you are accessing garbage value. 这是因为您正在访问垃圾值。 After nextToken() end up, token that's auto is deallocated,becoming garbage values to caller. 在nextToken()结束后,自动分配的令牌被释放,成为调用者的垃圾值。 For solve it, change life time of variable to static or do a dynamic memory allocation. 为了解决这个问题,可以将变量的生存期更改为静态或动态分配内存。 But as you know the size, it's may not prefered. 但是,正如您所知,它可能不是首选。 Just do: 做就是了:

static char token[50];

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

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