如何使用C中的动态数组解决realloc()无效的下一个大小错误?

我将通过说我对C还是很陌生,并且对malloc / realloc等没有太多的经验来对此做个开头。我目前正在尝试使用一个800磁道的磁盘对磁盘调度(FCFS)进行此分配模拟。数组作为跟踪请求队列。无论如何,运行程序时出现此错误:

“ ./ a.out”中的错误:realloc():无效的下一个大小:0x0000000000650010已终止

我并不感到惊讶,因为我知道动态数组确实不应该成为问题,但是不幸的是,这是我的分配工作。修复此错误的任何帮助将不胜感激。谢谢!

#include <stdio.h>
#include <math.h>
#include <stdlib.h>
#include <values.h>
#include <time.h>
#include <stdbool.h>

/* function declarations */
int trackReqs();
int numTrack();
void AddToList(int trackNum);
int RemoveFromList();

// global variable declarations/initializations
unsigned seed;
int fileReqs;
bool first = true;
int queue_size = 0;
int* req_queue = NULL; // dynamic array declaration to hold request queue.

void main(){
  printf("Seed for the random number generator: ");
  scanf("%d",&seed);
  srand(seed);
  printf("\n");
  printf("Number of file requests: ");
  scanf("%d",&fileReqs);
  printf("\n");

  req_queue = malloc(sizeof(int)); // allocate memory for the queue array (initially 4 bytes for 1 integer)

  // local variable declarations/initializations
  int totalReqs = 0;
  int numFileReqs = 0;
  float totalHeadmove = 0;
  int currTrack = 0;
  float diff;
  float average;

  do { // do this...
    int numTrackReqs = trackReqs(); // call function to get a random number between 1 and 5 to represent the number of track requests for the current file request
    for (int i = 0; i < numTrackReqs; i++) { // for each track request for the current file request...
      int trackNum = numTrack(); // call function to get a random number between 0 and 799 to represent the number of the track requested
      AddToList(trackNum); // call function to add the track request to the queue
      first = false;
    }
    int nextTrack = RemoveFromList(); // call function to remove the next (first) track request from the queue (signifying that the disk head will be moved to that track) and have that track returned
    diff = abs((float)nextTrack - (float)currTrack); // calculate the head movement for the current file request
    totalHeadmove += diff; // add the head movement for the current file request to the total head movement
    totalReqs++; // increase number of total requests by 1
    currTrack = nextTrack; // make the current track now the next track
    numFileReqs++; // increase number of file requests by 1
  } while(numFileReqs <= fileReqs); // ...for each file request
  average = totalHeadmove / (float) numFileReqs; // calculate the average total head movement for each file request and print the result
  printf("Average head movement: %5.2f",average);
}

int trackReqs(){
  int rand_num = (rand() % (5 - 1 + 1)) + 1; // generate random number from 1 to 5 representing number of track requests for the current file request
  return rand_num;
}

int numTrack(){
  int rand_num = rand() % 800; // generate random number from 0 to 799 representing
  return rand_num;
}

void AddToList(int trackNum){
  if(first != true){ // if it is not the first request being added to the queue...
    realloc(req_queue,sizeof(req_queue) + sizeof(int)); // increase capacity of queue array by 4 bytes (for 1 more integer)
    queue_size++; // increase size of queue by 1
  }
  req_queue[queue_size] = trackNum; // add request to the end of the queue
  return;
}

int RemoveFromList(){
  int first_req = req_queue[0]; // get first request in the queue
  if(queue_size == 0){ // if there is only 0 or 1 request in the queue...
    req_queue[0] = NULL; // make queue empty
  }
  else{
    for(int i = 0; i < queue_size - 1; i++){ // for each request in the queue...
      req_queue[i] = req_queue[i + 1]; // move up 1 position in the queue
    }
    realloc(req_queue,sizeof(req_queue) - sizeof(int)); // decrease capacity of queue array by 4 bytes (for 1 integer)
    queue_size--; // decrease size of queue by 1
  }
  return first_req;
}
linlin1988124 回答:如何使用C中的动态数组解决realloc()无效的下一个大小错误?

根据男人的话:

  

void * realloc(void * ptr,size_t size);   [...]

     

realloc()函数返回指向新分配的内存的指针,该指针适合于任何内置类型,并且可能是   与ptr不同,如果请求失败,则为NULL。

您的电话是

realloc(req_queue,sizeof(req_queue) + sizeof(int))

因此,您只需删除realloc的结果,并且由于旧指针可能变得无效,因此您正在访问无效的内存。

在我的机器上,编译器警告它:

 In function 'AddToList':
test.c:70:5: warning: ignoring return value of 'realloc',declared with attribute warn_unused_result [-Wunused-result]
   70 |     realloc(req_queue,sizeof(req_queue) + sizeof(int)); // increase capacity of queue array by 4 bytes (for 1 more integer)
      |     

^ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ ~~~~

顺便说一句,sizeof(req_queue)可能没有达到您的期望,它返回了req_queue的大小,这是一个指针,因此很可能是4或8(取决于您的系统)

编辑: 当您要求提供更多详细信息时,以下示例展示了您的add函数的外观:

void AddToList(int trackNum) {
    int *temp = realloc(req_queue,(queue_size + 1) * sizeof(int));
    if (temp != NULL) 
        req_queue = temp;
    else 
        return; // FIXME would need to handle error correctly here

    queue_size++; // increase size of queue by 1
    req_queue[queue_size - 1] = trackNum; // add request to the end of the queue
    return;
}

这里有两个要点: *您需要一个临时方法来获取realloc的返回值,因为如果分配失败,则需要保留旧指针,使其保持有效(请参见realloc(): invalid next size - realloc dynamic struct) *您需要跟踪已经分配的 size ,因此这里queue_size没问题,但是当您将其用作数组中的索引时,您可能会注意到我将其用作大小

您(在标准C语言中)无法直接从指针知道您分配的内存块的大小,您需要自己跟踪此大小。 (在BSD上,有非标准的malloc_size()AFAIR)

本文链接:https://www.f2er.com/3003624.html

大家都在问