c - 我用于获取单词的奇怪的非工作 C 代码

标签 c struct

有了这个结构定义:

struct word {
    char *cont; //content of the word
    char *wsp; //whitespace following the word
    int ctr;
};

总而言之,我正在尝试编写一个函数来从标准输入中获取第一个单词及其后的所有空格。在这里:

struct word *getword(){
    char cont[WORDLIM];
    char wsp[WORDLIM];
    cont[0] = '\0';
    wsp[0] = '\0';
    if (peekchar() == EOF) return NULL; //peekchar defined elsewhere as getting a char and ungetc-ing it

    REPEAT{ //macro for for(;;)
            char c = getchar();
            char buf[2];
            buf[0]=c;
            buf[1]='\0';
            if (c == '\n' || c == ' '){
                    strcat(wsp, buf);
                    if (peekchar() != '\n' && peekchar() != ' '){
                            struct word *toret;
                            toret = malloc(sizeof(struct word));
                            toret->cont = cont;
                            toret->wsp = wsp;
                            toret->ctr = -1;
                            printf("---%s---\n", toret->wsp); //just for debugging
                            return toret;
                    }
                    continue;
            }
    }
    printf("PANIC PANIC PANIC THIS IS GOING WROOOOONG!!!!!\n");
    return NULL;
}

现在有趣的是,我可以在 just for debugging 行中获得正确的空白输出,但是当我尝试访问 getword()->wsp 时,我得到随机垃圾。更有趣的是,getword()->cont 工作...

我是 C 语言的新手...我做错了什么?

最佳答案

您正在返回指向超出范围的内存的指针。

您动态分配一个struct word,但实际的字符保存在wsp 数组中。一旦您的函数返回,它就超出了范围,因此可以包含任何内容。

关于c - 我用于获取单词的奇怪的非工作 C 代码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14590867/

相关文章:

c - C 中 _int8 数据类型的格式说明符

c - 负数右移

c - 我不知道C中的 'glibc detected'

我可以在 C 结构中声明结构引用的动态数组吗?

c# - 将 Color32[] 数组快速复制到 byte[] 数组

使用 fork 创建子项并出现段错误(核心转储)

c - GDB,中断条件,检查空指针

创建 I2C 设备驱动程序结构设置

c++ - 如何在 SystemC 中使用结构作为信号类型?

c - 如何将字符串数组的值复制到字符数组?