"Program has triggered a breakpoint"时可用内存分配错误



当我释放内存时,出现错误"程序已触发断点"。检查下面的代码,我想知道哪里出了问题?

int SSavep(char *visited, int t, int n, int m)
{ 
int* map = (int*)malloc(m*n * sizeof(int));
int* q = (int*)malloc(m*n * sizeof(int));
int count = 0, cur = 0;
int begin = 0, end = 0;
for (int i = 0; i < m; i++) {
for (int j = 0; j < n; j++) {
//set value for map
}
}
..........
if (t >= map[end]) {
free(map);
free(q);
return 0;
}
else{
free(map);
free(q);
return -1;
}
}  

整个代码如下:

static int dir[4][2] =

{ {0,1},{0,-1},{1,0},{-1,0} };int SSavep(char *visited, int t, int n, int m( {

int* map = (int*)malloc(m*n * sizeof(int));
int* q = (int*)malloc(m*n * sizeof(int));
int count = 0, cur = 0;
int begin = 0, end = 0;
for (int i = 0; i < m; i++) {
for (int j = 0; j < n; j++) {
if (visited[i*n + j] == '.')
map[i*n + j] = 0;
else if (visited[i*n + j] == '*')
map[i*n + j] = -1;
else if (visited[i*n + j] == 'p') {
map[i*n + j] = -12;
end = i*n + j;
}
else {
map[i*n + j] = -9;
begin = i*n + j;
}   
}
}
q[count++] = begin;
while (cur < count && q[cur] != end) {
int i = q[cur] / n;
int j = q[cur] % n;
for (int k = 0; k < 4; k++) {
int ni = i + dir[k][0];
int nj = j + dir[k][1];
if (ni < 0 || ni >= m || nj < 0 || nj >= n || map[ni*n + nj]>0 || map[ni*n + nj] == -1)
continue;
map[ni*n + nj] = map[i*n + j] + 1;
q[count++] = ni*n + nj;
}
cur++;
}
if (map[end] > 0 && t >= map[end]) {
free(map);
free(q);
return 0;
}
else{
free(map);
free(q);
return -1;
}

}

你在>> free(q( 上收到错误;

for m=n=4
int* q = (int*)malloc(m*n * sizeof(int));
q == [m*n*sizeof(int)] == 4*4*4 == 64 bytes == int[16];

因为您在为指针变量"q"保留的地址空间之外写入。 在 free(q( 之前检查"计数"变量。我有 1208,打电话给:

char* visited = new char[100 * 100];
memset(visited, 0, 10000);
int res = SSavep(visited, 0, 4, 4);

顺便说一句,这个算法看起来很像一些路径查找,检查地图上的相邻单元格并分配权重,对吧?如果是这样,有很多开源解决方案,为什么不使用它们而不是重新发明轮子呢?在wiki路径查找页面上有开源解决方案的链接:

https://en.wikipedia.org/wiki/Pathfinding

检查页面底部的链接。

相关内容

  • 没有找到相关文章

最新更新