繁体   English   中英

两次重新分配错误…?

[英]Double realloc error…?

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

码:

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重新规划: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)(已创建内存打印)

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

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

graph[*stationCount] = newStation;

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

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

graph[newCount-1] = newStation;

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM