【发布时间】:2021-09-05 01:20:43
【问题描述】:
我有一个结构:
typedef struct cellNode {
int cell;
struct cellNode* next;
} Node;
typedef struct {
int numRows;
int numColumns;
Node** rows;
} Matrix;
还有一个在我的代码中添加节点的函数,但是当我尝试为函数内的节点分配内存时出现 0xC0000005 错误:
Node* createNode()
{
int n;
Node* newNode = malloc(sizeof(Node));
if (newNode==NULL)
exit(1);
scanf("%d",&n);
printf("n is %d\n",n);
newNode->cell=n;
newNode->next = NULL;
return newNode;
}
该函数为节点分配内存并将其返回给另一个函数,该函数将其附加到节点数组中。所以对 createNode 函数的调用如下所示:
Matrix* MatrixAdder(int row, int col, char mat)
{
int i,j;
int value=0;
Node* newNode=NULL;
Matrix* temp = malloc(sizeof(Matrix));
if (temp==NULL)
exit (1);
temp->numRows=row;
temp->numColumns=col;
temp->rows = malloc(row * sizeof(Node*));
if (temp->rows==NULL)
exit(1);
for (i=0;i<row;i++)
{
printf("Enter row %d data\n",i);
scanf("%d",&value);
temp->rows[i]->cell=value;
for (j=0;j<col-1;j++)
{
newNode=createNode();
temp->rows[i]->next=newNode;
}
}
}
我明白了:
Enter row 0 data
2
Process returned -1073741819 (0xC0000005) execution time : 6.525 s
Press any key to continue.
该函数能够接收 int,但在 malloc 行立即失败。 main 只是调用函数:
int main()
{
int i;
Matrix *A, *B, *C;
int n,m,k;
MatSize(&n,&m,&k); /*works fine*/
A=MatrixAdder(n, m, 'A');
B=MatrixAdder(m, k, 'B');
return 1;
}
【问题讨论】:
-
你能把它放在minimal reproducible example 中,这样我们就可以看到整个画面了吗?
-
Cannot reproduce。请提供正确的minimal reproducible example,否则我们将无法提供帮助。
-
向我们展示“其他地方”,我们会指出如何。
-
但是错误来自这个函数,所以其他地方的问题是什么你以某种方式破坏了内存。当您的
malloc()呼叫踏上您在破坏内存时埋下的地雷时,您的进程就会爆炸。 -
CreateNode != newNode.