在 C 中返回动态分配的结构时出现未处理的异常
Unhandled exception when returning a dynamically allocated struct in C
对于我 运行 遇到的问题,我还没有找到类似的问题。我只是在猜测错误的根源,但我没有足够的知识来调试它。代码如下:
main.c
#include <stdio.h>
#include "adjacency.h"
int main()
{
FILE* textfile;
textfile = fopen("graf.txt", "r");
adjacency_matrix Graph;
create_graph(textfile);
}
adjacency.c
#include "adjacency.h"
#include <stdlib.h>
#include <stdio.h>
adjacency_matrix create_graph(FILE* input)
{
adjacency_matrix graph; int s_node, f_node;
fscanf(input, "%d", &graph.vertices);
int i, j;
graph.matrix = (int**)malloc((graph.vertices + 1) * sizeof(int*));
for (i = 0; i <= graph.vertices; i++)
graph.matrix[i] = (int*)malloc(sizeof(int));
for (i = 0; i <= graph.vertices; i++)
for (j = 0; j <= graph.vertices; j++)
graph.matrix[i][j] = 0;
for (i = 0; i <= graph.vertices; i++)
graph.matrix[i][0] = graph.matrix[0][i] = i;
while (1)
{
fscanf(input, "%d %d", &s_node, &f_node);
if (feof(input))
break;
graph.matrix[s_node][f_node] = 1;
}
return graph;
}
一切正常(我已经测试过在返回图形结构之前在函数内部打印矩阵),但它在返回主源文件中我的函数调用的 adjacency_matrix 结构后停止。
Visual Studio 说
Unhandled exception at 0x77F4A879 (ntdll.dll) in dijkstra.exe: 0xC0000374: A heap has been corrupted (parameters: 0x77F85910).
然后将我指向第 292 行的 exe_common.inl。
if (!has_cctor)
_cexit();
非常感谢您的帮助。
我认为您需要为矩阵的列分配更多内存:
for (i = 0; i <= graph.vertices; i++)
graph.matrix[i] = (int*)malloc((graph.vertices + 1) * sizeof(int));
对于我 运行 遇到的问题,我还没有找到类似的问题。我只是在猜测错误的根源,但我没有足够的知识来调试它。代码如下:
main.c
#include <stdio.h>
#include "adjacency.h"
int main()
{
FILE* textfile;
textfile = fopen("graf.txt", "r");
adjacency_matrix Graph;
create_graph(textfile);
}
adjacency.c
#include "adjacency.h"
#include <stdlib.h>
#include <stdio.h>
adjacency_matrix create_graph(FILE* input)
{
adjacency_matrix graph; int s_node, f_node;
fscanf(input, "%d", &graph.vertices);
int i, j;
graph.matrix = (int**)malloc((graph.vertices + 1) * sizeof(int*));
for (i = 0; i <= graph.vertices; i++)
graph.matrix[i] = (int*)malloc(sizeof(int));
for (i = 0; i <= graph.vertices; i++)
for (j = 0; j <= graph.vertices; j++)
graph.matrix[i][j] = 0;
for (i = 0; i <= graph.vertices; i++)
graph.matrix[i][0] = graph.matrix[0][i] = i;
while (1)
{
fscanf(input, "%d %d", &s_node, &f_node);
if (feof(input))
break;
graph.matrix[s_node][f_node] = 1;
}
return graph;
}
一切正常(我已经测试过在返回图形结构之前在函数内部打印矩阵),但它在返回主源文件中我的函数调用的 adjacency_matrix 结构后停止。
Visual Studio 说
Unhandled exception at 0x77F4A879 (ntdll.dll) in dijkstra.exe: 0xC0000374: A heap has been corrupted (parameters: 0x77F85910).
然后将我指向第 292 行的 exe_common.inl。
if (!has_cctor)
_cexit();
非常感谢您的帮助。
我认为您需要为矩阵的列分配更多内存:
for (i = 0; i <= graph.vertices; i++)
graph.matrix[i] = (int*)malloc((graph.vertices + 1) * sizeof(int));