2013-10-25 44 views
0

我的程序崩溃,并显示下列行:堆大小错误字符串

警告

: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; 

}

我的程序做的逻辑,然后试图释放内存崩溃后分配空间。

+2

在C中,不要投入malloc :http://stackoverflow.com/questions/605845/do-i-cast-the-result-of-malloc – Barmar

+0

你的意思是说,当你想释放权利时你会崩溃? – ncm

+0

你确定问题不在'CallSomeFunctionHere'里面吗?还要注意'CallSomeFunctionHere'在循环之外,这是你想要的吗? “col”究竟意味着什么?最大。字符串长度?如果是这样,你忘记了空终止符的空间。 –

回答

0

你忘了在字符串结尾的空分配空间:

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

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

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

既然你是路过maze[i]scanf作为%s目标,你需要额外拨款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); 
+0

非常感谢你的帮助它解决了问题! – cat

+0

@cat不客气!如果问题现在已解决,请考虑通过点击旁边的灰色复选标记来接受答案。这可以让网站的其他访问者知道您不再需要寻找改进的解决方案,并且可以在Stack Overflow上为您获得新徽章。 – dasblinkenlight

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

你不为一个字符串结束分配空间。更改为:

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

注意sizeof(char)是1定义,并且你不需要从malloc类型转换的返回值。

有2个地方的缓冲区可以得到溢出:

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

变化:

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

最后一个地方是:

CallSomeFunctionHere(maze); 

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