双重realloc错误......?

时间:2013-09-30 10:43:51

标签: c realloc

我有一个用于扩展数组(图形)的函数,并在最后添加一个新值。对函数的第一个请求很顺利,但是当我第二次执行时会出现问题......

代码:

struct station *addStation(struct station *graph, struct station newStation, size_t  *stationCount){
  size_t newCount = *stationCount+1;

  graph = realloc(graph, newCount*sizeof(struct station));
  *stationCount = newCount;

  graph[*stationCount] = newStation;

  return graph;
}

和请求:

  Station *graph;
  graph = malloc(146*sizeof(Station));

  graph = loadStations(graph, &stationCount);

  Station newStation = graph[0]; // Dummyvalue

  printf("StationCount:%d\n",stationCount);

  graph = addStation(graph, newStation, &stationCount);

  printf("StationCount:%d\n",stationCount);

  graph = addStation(graph, newStation, &stationCount);

由于第二行graph = addStation ...终端中出现了一些内存输出错误:

StationCount:146 StationCount:147 reseplanerare:malloc.c:2369:sysmalloc:断言`(old_top ==(((mbinptr)(((char *)&((av) - > bins [((1) - 1)* 2])) - __builtin_offsetof(struct malloc_chunk,fd))))&& old_size == 0)|| ((unsigned long)(old_size)> =(unsigned long)(((__ builtin_offsetof(struct malloc_chunk,fd_nextsize))+((2 *(sizeof(size_t))) - 1))&〜((2 * (sizeof(size_t))) - 1)))&&((old_top) - > size& 0x1)&&((unsigned long)old_end& pagemask)== 0)'失败。 中止(SIGABRT)(创建内存打印)

我不明白为什么会这样......

1 个答案:

答案 0 :(得分:3)

C数组从零开始,因此graph具有有效索引[0..newCount-1]

graph[*stationCount] = newStation;

写入超出分配内存的末尾。这导致未定义的行为。我想在你的情况下,它正在破坏堆管理器用来检测这种内存损坏的保护字。

您可以通过更改您写入的数组索引来解决此问题:

graph[newCount-1] = newStation;