gpt4 book ai didi

c - malloc 运行时错误

转载 作者:太空宇宙 更新时间:2023-11-04 01:25:37 25 4
gpt4 key购买 nike

#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]);
}

最佳答案

问题是你有:

*output[i]

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

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

double *output;

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

关于c - malloc 运行时错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31505485/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com