c - 使用 malloc 时出错

标签 c malloc

我通过char ** input来自 main()processInExp()函数,然后我再次从 processInExp() 传递它函数到 getInput()函数在读取文件时动态分配它。

内部 getInput()功能 input检查时已正确分配内存,但在 in processInExp() 中使用它时它遇到运行时错误。可能是什么问题?

下面是我的代码:

int getInput(char ** input, const char * fileName)
{
    int numInput = 0;
    int i, j;
    char c;
    char tempInput[100];
    FILE * pFile;
    if((pFile = fopen(fileName, "r")) == NULL)
    {
        printf("Cannot read file %s\n", fileName);
        system("PAUSE");
        exit(1);
    }
    while(!feof(pFile))
    {
        c = fgetc(pFile);
        if(c == '\n') ++numInput;

    }
    /* printf("%d\n", numInput); */
    input = (char**)malloc(numInput * sizeof(char*)); /* #2 MALLOC input */
    rewind(pFile);
    for(i = 0; !feof(pFile); ++i)
    {
        fscanf(pFile, "%[^\n]%*c", tempInput);
        /* printf("%s\n", tempInput); */
        input[i] = (char*)malloc((strlen(tempInput) + 1) * sizeof(char)); /* #3 MALLOC input[] */
        strcpy(input[i], tempInput);
        /* printf("%s\n", input[i]); */ /* #4 PRINT OUT PERFECTLY */
        memset(tempInput, 0, sizeof(tempInput));
    }
    fclose(pFile);
    return numInput;
}
void processInExp(char ** input, char ** output, const char * fileName)
{
    int numFormula;
    int i;

    numFormula = getInput(input, fileName); /* #1 PASSING input */
    /* printf("%s\n", input[0]); */ /* #5 RUNTIME ERROR */
    output = (char**)malloc(numFormula * sizeof(char*));
    system("PAUSE");

    for(i = 0; i < numFormula; ++i)
    {
        convertIntoPost(input[i], output[i]);
        printf("%d. %s -> %s", (i + 1), input[i], output[i]);
    }

}

最佳答案

C使用按值传递函数参数传递。所以,从函数内部 getInput() ,您无法更改变量 input并期望该更改反射(reflect)在传递给函数的实际参数中。为此,您需要传递一个指向变量的指针,就像在这种情况下,您需要这样做

   int getInput(char *** input, const char * fileName) { //notice the extra *

并且需要像这样称呼它
   char ** inp = NULL;
   getInput(&inp, ..........);

然后,getInput()将能够将内存分配给 *input函数内部将反射(reflect)到 inp .

否则,从getInput()返回后,实际参数仍将未初始化并进一步使用(在您的情况下,在 for 函数中的 processInExp() 循环中)将导致 undefined behaviour .

也就是说,还有两件重要的事情需要注意,
  • see why not to cast malloc() 的返回值和家人在C .
  • 查看Why is while ( !feof (file) ) always wrong?
  • 关于c - 使用 malloc 时出错,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31470053/

    相关文章:

    c - 如何使用函数指针执行算术运算?

    java - JNI添加jar库的问题

    c - 帮助 C 指针

    c - 使用结构编程简单存储学生信息

    objective-c - 自由函数在 c/objective-c 中不起作用

    c - C 中 void * 转为 char 或 int

    c - 从函数返回结构元素的 malloc

    c++ - Redis命令ERR:参数数量不正确hiredis

    c - 将指针传递给函数会导致在 C 中读取无法访问的地址

    c - 为什么空闲列表没有排序?