【问题标题】:HEAP size error stringsHEAP 大小错误字符串
【发布时间】:2013-10-25 10:39:20
【问题描述】:

我的程序因以下几行而崩溃:

警告:HEAP[maze.exe]: 警告:00392F30 处的堆块在 00392F3B 处修改,超过请求的 3 大小

我正在为字符串动态分配空间

int userReq() {
char **maze=NULL;
char *pchar;
int i, test_cases, cur_test=0;
int row, col;

/* gather the amount of test cases */
scanf("%d", &test_cases);
do{
    scanf("%d",&row);
    scanf("%d",&col);
    /* allocate memory for char pointer row-wise */
    maze = (char **) malloc(row*sizeof(char*));

    for(i=0;i<row;i++)
        /* for each cell allocate the num of chars in cell */
        maze[i] = (char *) malloc(col*sizeof(char));

    for(i=0;i<row;i++) 
        scanf("%s",maze[i]);
            /* this function does modify the maze by changing some of the spots to a different char */
            CallSomeFunctionHere(maze);


    /* free first the cells then the entire block */
    for(i=0;i<row;i++)
        free(maze[i]);
    free(maze);

    cur_test = cur_test + 1;

}while(cur_test < test_cases);

/* if we were successful then exit program with
success */
return 0;

}

我的程序在执行逻辑然后尝试释放内存后崩溃。

【问题讨论】:

  • 在 C 中,不要强制转换 malloc:stackoverflow.com/questions/605845/…
  • 你的意思是你想释放的时候就崩溃了对吧?
  • 您确定问题不在CallSomeFunctionHere 内部吗?另请注意,CallSomeFunctionHere 在循环之外,这是您想要的吗? col 到底是什么意思?最大限度。字符串长度?如果是这样,您忘记了空终止符的空间。
  • 我建议使用valgrind 并花一些时间使用它

标签: c


【解决方案1】:

这意味着您请求的内存比您需要的少。最可能的罪魁祸首是这一行:

maze[i] = (char *) malloc(col*sizeof(char));

由于您将maze[i] 作为%s 目标传递给scanf,因此您需要为空终止符分配一个额外的char

将输入限制在您分配的范围内是一个非常好的主意。考虑使用fgets 而不是scanf

for(i=0;i<row;i++) 
    fgets(maze[i], col+1, stdin);

附:在 C 中,您不需要强制转换 malloc。你也不需要乘以sizeof(char),因为标准要求它是1

maze[i] = malloc(col+1);

【讨论】:

  • 非常感谢您帮助它解决了问题!
  • @cat 欢迎您!如果问题现在已解决,请考虑通过单击旁边的灰色复选标记来接受答案。这将使该网站的其他访问者知道您不再积极寻找改进的解决方案,并为您赢得 Stack Overflow 上的新徽章。
【解决方案2】:
    maze[i] = (char *) malloc(col*sizeof(char));

您没有为字符串终止符分配空间。改为:

    maze[i] = malloc(col + 1); 

请注意,sizeof(char) 根据定义为 1,您无需对来自 malloc 的返回值进行类型转换。

有两个地方会导致缓冲区溢出:

    scanf("%s",maze[i]); 

改为:

    scanf("%.*s", col, maze[i]);

最后一个地方是:

    CallSomeFunctionHere(maze);

(我没有这个的源代码。)

【讨论】:

    【解决方案3】:

    您忘记为字符串中的尾随 null 分配空间:

    maze[i] = malloc((col+1)*sizeof(char));
    

    【讨论】:

      猜你喜欢
      • 2021-07-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-01-15
      • 1970-01-01
      • 2022-12-17
      • 1970-01-01
      相关资源
      最近更新 更多