【发布时间】:2015-09-29 23:09:31
【问题描述】:
请注意静态变量selection。
我正在测试选择是否在不同范围内分配了正确的字符字符串。
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
static char* selection;
static char* sel_item(char* text)
{
char* pch;
char buf[80];
strcpy(buf, text);
pch = strtok(buf, " ");
return pch;
}
static int display_ecnt_codes(char* text)
{
char buf[80];
strcpy(buf, text);
selection = sel_item(buf);
// why if I output the selection here, the selection is random char, not the correct char "SRFPRO".
// printf("display_ecnt_codes: %s\n", selection);
}
int acode_prockey()
{
char text[] = "SRFPRO - Surface Protection (DealerProduct)";
display_ecnt_codes(text);
// why if I output the selection here, it prints the correct char string "SRFPRO".
// what's the difference between this scope and the above scope?
printf("acode_prockey: %s\n", selection);
}
int main ()
{
acode_prockey();
// it will output SRFPRO, the first token of the char text[].
printf("main: %s\n", selection);
}
我希望有人可以解释全局静态变量“选择”。 当我在函数“display_ecnt_codes”中打印它时,它会输出随机字符。如果我不在函数内部打印它,它会在主函数中输出正确的字符。
【问题讨论】:
-
Dangling Pointer in C 的可能重复项
-
sel_item 返回后,buf 不再存在(因为 buf 是存储在堆栈上的局部变量)。因此 pch (指向 buf 内部的某个位置)是无效的,并且您正在调用未定义的行为(任何事情都可能发生,您的程序可能会崩溃等)。您需要使用 malloc 分配 sel_item 中的 buf(并且不要忘记释放!)。我建议更多地了解 C 中的内存分配和生命周期是如何工作的。
标签: c