-1

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

代码:

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);

由于第二条线图 = addStation... 我在终端中收到一些内存输出错误:

StationCount:146 StationCount:147 reseplanerare: malloc.c:2369: sysmalloc: Assertion `(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)(已创建内存打印)

我不明白为什么会发生这种情况......

4

1 回答 1

3

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

graph[*stationCount] = newStation;

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

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

graph[newCount-1] = newStation;
于 2013-09-30T10:45:25.697 回答