malloc

时间:2015-07-19 20:11:26

标签: c malloc runtime-error

#define MAXL 256

我认为我的代码的问题是eventho numInput = 3,不知何故,output[2]不存在,所以当我尝试分配它时,程序崩溃(只是猜测)。

有没有办法检查ouput[2]是否存在?或者也许有人能够找到我的代码的真正问题,这将是非常棒的!

非常感谢任何帮助!

注意:我投射malloc的原因是我的讲师所期望的。

Input strings are: 25 7 * 14 - 6 +
                   1 24 3 + * 41 -
                   2 37 4 + * 15 +

void processPostfixExp(const char * fileName)
{
    char ** input = NULL;
    double ** output = NULL;
    int i = 0, numInput = 0;
    char tempInput[MAXL] = {0};
    FILE * pFile = NULL;

    /* Get number of strings, check if file is readable and open file */    
    numInput = checkFile(fileName);
    pFile = fopen(fileName, "r"); 

    /* Allocate memory for the string storages and alert if fail */
    input = (char**)malloc(numInput * sizeof(char*));
    output = (double**)malloc(numInput * sizeof(double*));
    if(!input || !output)
    {
        printf("Memory allocation failed.\n");
        system("PAUSE");
        exit(1);
    }

    /* Scan the file by lines and duplicate the string to input storage */
    for(i = 0; i < numInput; ++i)
    {
        fgets(tempInput, MAXL, pFile);
        tempInput[strlen(tempInput)-1] = '\0';
        input[i] = strdup(tempInput);
        //printf("\n%s", input[i]);
    }

    /* Close file and clear screen */
    fclose(pFile);
    system("CLS");

    /* Call converter and display result */
    printf("-------------------------------------------------------\n");
    printf("\nPostfix expression evaluation:\n");
    for(i = 0; i < numInput; ++i) 
    {
        printf("input = %s", input[i]); /* i = 2 Printf SUCCESS */
        *output[i] = evaluatePost(input[i]); /* i = 2 CRASH HERE */
        /* I added a check at the top most of the evaluatePost(), program did not get to there */
        //printf("\nCase %d: %s\nResult:%.2f\n", i + 1, input[i], *output[i]);
    }
    printf("\n");
    printf("-------------------------------------------------------\n");
}

更新:

所以我添加了这些行并且可以确认输出[2]不存在......这怎么可能?请帮忙,谢谢!

for(i = 0; i < numInput; ++i)
    {
        *output[i] = (double)i;
        printf("output[%d] = %.1f\n", i, *output[i]);
    }

2 个答案:

答案 0 :(得分:4)

问题是你有:

*output[i]

您已将numInput指针分配为double,但指针本身并不存在。

看起来你想分配空间不是为了指针,而是为了双打:

double *output;
…
output = (double*)malloc(numInput * sizeof(double));

答案 1 :(得分:0)

我不确定您对evaluatePost()的调用有什么问题,特别是因为您没有为该函数提供原型。

但是,总体而言,您的代码应类似于以下内容:

将来,请发布(独立)实际干净编译的代码 当您需要有关运行时问题的帮助时。

强烈建议在启用所有警告的情况下进行编译。

对于gcc,至少要使用&#39; -Wall -Wextra -pedantic&#39;

处理错误时,请始终清理已分配的内存,打开文件等

#define  _POSIX_C_SOURCE (200809L)
#include <stdio.h>
#include <stdlib.h> // exit() and EXIT_FAILURE
#include <string.h> // memset() and strdup()

#define MAXL (256)

// prototypes
int     checkFile( const char * );
double  evaluatePost( char * );

void processPostfixExp(const char * fileName)
{
    char   **input = NULL;
    double **output = NULL;

    int    i = 0;
    int    numInput = 0;
    char   tempInput[MAXL] = {0};
    FILE   *pFile = NULL;

    /* Get number of strings, check if file is readable and open file */
    numInput = checkFile(fileName);
    if( NULL == (pFile = fopen(fileName, "r") ) )
    { // then fopen failed
        perror( "fopen for input file failed" );
        exit( EXIT_FAILURE );
    }

    /* Allocate memory for the string storages and alert if fail */
    if( NULL == (input = malloc(numInput * sizeof(char*)) ) )
    { // then malloc failed
        perror( "malloc for input failed" );
        fclose( pFile );
        exit( EXIT_FAILURE );
    }

    // implied else, malloc successful

    memset( input, 0x00, numInput*sizeof(char*) ); // to make later free() operation easy

    if( NULL == (output = malloc(numInput * sizeof(double*)) ) )
    { // then malloc failed
        perror( "malloc for output failed" );
        fclose( pFile );
        free( input );
        exit( EXIT_FAILURE );
    }

    // implied else, malloc successful

    memset( output, 0x00, numInput * sizeof(double*) ); // to make later free() operation easy

    /* Scan the file by lines and duplicate the string to input storage */
    for(i = 0; i < numInput; ++i)
    {
        if( NULL == fgets(tempInput, MAXL, pFile) )
        { // then fgets failed
            perror( "fgets for input file failed" );
            fclose( pFile );
            for( int j=0; j<numInput; j++ )
            {
                free( input[j] );
                free( output[j] );
            }
            free( input );
            free( output );
            exit( EXIT_FAILURE );
        }

        // implied else, fgets successful

        char * offset = NULL;
        if( NULL != (offset = strstr( tempInput, "\n" )) )
        { // then newline found
            *offset = '\0';
        }

        if( NULL == (input[i] = strdup(tempInput) ) )
        { // then strdup failed
            perror( "strdup for input line failed" );
            fclose( pFile );
            for( int j=0; j<numInput; j++ )
            {
                free( input[j] );
                free( output[j] );
            }
            free( input );
            free( output );
            exit( EXIT_FAILURE );
        }

        //printf("\n%s", input[i]);
    } // end for

    /* Close file and clear screen */
    fclose(pFile);
    system("CLS");

    /* Call converter and display result */
    printf("-------------------------------------------------------\n");
    printf("\nPostfix expression evaluation:\n");
    for(i = 0; i < numInput; ++i)
    {
        printf("input = %s", input[i]); /* i = 2 Printf SUCCESS */
        *output[i] = evaluatePost(input[i]); /* i = 2 CRASH HERE */
        /* I added a check at the top most of the evaluatePost(), program did not get to there */
        //printf("\nCase %d: %s\nResult:%.2f\n", i + 1, input[i], *output[i]);
    }
    printf("\n");
    printf("-------------------------------------------------------\n");

    for( int j=0; j<numInput; j++ )
    {
        free( input[j] );
        free( output[j] );
    }
    free( input );
    free( output );
} // end function: processPostfixExp