我需要重新分配一个字符矩阵,但它不起作用。
我尝试了很多解决方案,但没有一个有效。
程序可以编译,但运行后在 realloc() 上崩溃。
#include <stdio.h>
#include <stdlib.h>
typedef struct Xy {
int x;
int y;
}Xy;
typedef struct Nodo{
Xy destination;
struct Nodo *next;
}Nodo;
char **matrD;
char **matrU;
char **matr;
int i,j;
Nodo *header;
Xy pos;
Xy dimD;
Xy dimU;
Xy startD;
Xy startU;
Xy *dim;
Xy *start;
char flor='d';
int *dimen;
int dimenD[]={10,6};
int dimenU[]={10,6};
int gradi=0;
char sens[4];
void addCol(){
int newsize=dim->x+2;
for(i=0;i<dim->y;i++){
printf("ciao\n");
printf("%d",newsize);
printf("%c\n",matr[i]);
matr[i]=realloc(matr[i],sizeof(char)*newsize); <-----it crash here
printf("ciao\n");
}
dim->x=dim->x+2;
}
void addRow(){
dim->y=dim->y+2;
// matr= (char*)realloc(matr,dim->y);
}
void loop() {
addCol();
// stampamatrix();
}
void main() {
sens[0]='t';
startD.x=0;
startD.y=0;
startU.x=0;
startU.y=0;
pos.x=0;
pos.y=0;
dimD.x=1;
dimD.y=1;
dimU.x=0;
dimU.y=1;
dim=&dimD;
dimen=dimenD;
start=&startD;
matrD =malloc(sizeof(char*)*dimD.x);
matrD[0] =malloc(sizeof(char)*dimD.x);
matrU =malloc(sizeof(char*)*dimU.y);
matrU[0] =malloc(sizeof(char)*dimU.x);
loop();
}
最佳答案
问题是你没有在任何地方初始化matr
,这意味着它是一个空指针(因为它是一个全局变量,所以它是“零初始化”,这意味着NULL
用于指针)。
因此,当您尝试使用例如取消引用 matr
时, matr[i]
那么你将会有未定义的行为并且很可能会崩溃。
你应该学习如何使用调试器,因为那样这个问题就会非常明显。在调试器中运行将使调试器在崩溃发生时在崩溃位置停止。然后,它将允许您遍历函数调用堆栈,以便到达您的代码(如果调试器尚未在您的代码处停止),然后您可以检查所涉及参数的值。在调试器中检查 matr[i]
会导致调试器告诉您这不是一个有效的指针,并且您很快就会看到这个问题,而无需任何帮助。
关于c - Realloc 使我的程序崩溃,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36082894/