Search code examples
cmemory-managementmalloc

Why does malloc throw a "corrupted top size" error when memory is allocated for a struct?


I have a struct that I am using, and I have written a method to create and initialize it. The method throws a corrupted top size error when I malloc memory for the struct. Here is the code for the struct:

typedef struct Job {
  int id;
  int cpuBurst;
  int ioBurst;
  int repetitions;
  int priority;
  int startTime;
  int endTime;
  int waitTime;
}Job;

and the method:

Job * createJob(int id, int cpuBurst, int ioBurst, int repetitions, int priority) {
  Job *job = (Job *) malloc(sizeof(Job));
  job->id = id;
  job->cpuBurst = cpuBurst;
  job->ioBurst = ioBurst;
  job->repetitions = repetitions;
  job->priority = priority;
  job->startTime = -1;
  job->endTime = -1;
  job->waitTime = 0;
  
  return job;
}

Job *job = (Job *) malloc(sizeof(Job)); throws the error.

I have looked around for similar questions, but all the ones I could find had to do with buffer overflow, and I don't think that's my problem as I'm not using a buffer.


Solution

  • That error (corrupted top size) is the sort of error you get if something has already corrupted the heap before your malloc call. It's usually the malloc code checking its internal data structures for sanity before potentially causing more damage.

    You probably need to look at other code to find out why since, aside from one issue (see below), your code is safe.


    As an aside, you shouldn't explicitly cast the return value of malloc in C, it's not necessary and it can hide certain subtle bugs.

    And you should definitely compare the return value against NULL before attempting to use it. Failing to do so will likely also crash your code.