c - Realloc 使我的程序崩溃

标签 c realloc

我需要重新分配一个字符矩阵,但它不起作用。

我尝试了很多解决方案,但没有一个有效。

程序可以编译,但运行后在 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/

相关文章:

ruby-on-rails - 是否支持在 Heroku 上使用 C 扩展 Ruby?

c - unix goto命令源代码

c - Mac OS 更新后,Strcpy 不适用于循环的第一行

将段落转换为具有动态内存的句子

c - 在函数中使用 realloc() 调整 int 指针大小时出现问题

c - 从数组读取段错误(可能与 malloc/realloc 相关)

可以在按下 enter 以外的某个特定键时终止 scanf

c - c中最有效的指针算术类型

c - 动态内存分配的二进制加法

c - "realloc(): invalid next size"是什么意思?