【问题标题】:static variable scope inside and outside the function函数内外的静态变量作用域
【发布时间】: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


【解决方案1】:

在以下函数中,您返回的指针在函数返回后无效。

static char* sel_item(char* text)
{
    char* pch;

    // An array on the stack
    char buf[80];
    strcpy(buf, text);

    // A pointer to some element of the array.
    pch = strtok(buf, " ");

    // Returns a pointer that is not valid after the function returns.
    return pch;
}

稍后,您将使用存储在selection 中的无效指针。因此,您的程序表现出未定义的行为。

【讨论】:

    猜你喜欢
    • 2012-04-30
    • 2017-05-27
    • 1970-01-01
    • 2013-11-04
    • 1970-01-01
    • 2016-08-30
    • 2016-04-27
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多