为什么getline在C函数中失败?

时间:2014-11-04 16:10:35

标签: c function pointers getline

我正在创建一个(非常)基本的shell - 但是,我是在偶然的基础上使用函数来改变全局变量 - 我被建议不要由年长且更聪明的程序员做 - 所以我已经着手改变这种行为返回指向变量的指针,而不是改变全局变量。

当我的程序运行getline时,读取数据的指针返回空,导致它在我稍后获取该字符串的副本时崩溃。我知道getline工作正常 - 但是离开方法时结果会丢失。为什么这样,我该如何解决?

非常感谢!

#define TRUE    1
#define FALSE   0

int readcmd(char* cmd, size_t nBytes);

int argCount = 0; //Counter of number of arguments

int readcmd(char *cmd, size_t nBytes) {

    int ret = getline(&cmd, &nBytes, stdin);

    printf("%s", cmd); //This prints correctly
    return ret;
}

int main() {
    const size_t nBytes = 64; //Data type representing size of objects (unsigned)

    char *cmd = NULL; //Pointer to input string
    char *cmdCpy = NULL;

    int bytesRead = -1;
    char prompt[] = "DaSh-> ";

    while (1) {

        printf("%s", prompt); //Print prompt

        bytesRead = -1;
        while (bytesRead == -1) {
            bytesRead = readcmd(cmd, nBytes); //While no bytes read, loop
        }

        printf("%s", cmd); //This prints "(null)" - data lost!?

        cmdCpy = malloc((sizeof(char) * bytesRead) + 1);
        strcpy(cmdCpy, cmd);

        return 0;
    }
}

3 个答案:

答案 0 :(得分:3)

getline的调用会修改cmd函数的本地readcmd变量。此更改在函数外部不可见,因此当控件返回main时,cmd变量仍保持不变。 nBytes变量也是如此。

要解决此问题,您可以通过指针将参数传递给readcmd函数:

int readcmd(char **cmd, size_t *nBytes) {
    int ret = getline(cmd, nBytes, stdin);

    printf("%s", *cmd); //This prints correctly
    return ret;
}

bytesRead = readcmd(&cmd, &nBytes);

但您也可以直接从getline调用main函数。

答案 1 :(得分:2)

试试这个:

注意malloc((sizeof(char)* bytesRead)+ 1)if bytesRead == -1

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

int readcmd(char **cmd, size_t *nBytes) {

    int ret = getline(cmd, nBytes, stdin);

    printf("%s", *cmd); //This prints correctly
    return ret;
}

int main() {
    const size_t nBytes = 64; //Data type representing size of objects (unsigned)

    char *cmd = NULL; //Pointer to input string
    char *cmdCpy = NULL;

    int bytesRead = -1;
    char prompt[] = "DaSh-> ";

    while (1) {

        printf("%s", prompt); //Print prompt

        bytesRead = -1;
        while (bytesRead == -1) {
            bytesRead = readcmd(&cmd, &nBytes); //While no bytes read, loop
        }

        printf("%s", cmd); //This prints "(null)" - data lost!?

        cmdCpy = malloc((sizeof(char) * bytesRead) + 1);
        strcpy(cmdCpy, cmd);

        return 0;
    }
}

bytesRead = readcmd(&amp; cmd,&amp; nBytes)如果要保留数据,则应传递地址。

答案 2 :(得分:0)

第一次调用readcmd()时,cmd的值为null,并且没有分配任何存储空间,因此getline()将失败。