0

So, I'm working on a course database project, where I have an array of pointers that point to my struct "class_t".

typedef struct class
{
  char dept[MAX_DEPT_CHARS]
  char coursenum[MAX_COURSE_DIGITS]
  char location[MAX_LOCATION_CHARS]
} class_t



class_t *classes[MAX_CLASSES];

where MAX_CLASSES is 64. In the program I have to malloc some memory whenever a new class is added to the array. a tad later in the program, i ask the user to make a choice on what they want to do. one of the choices is to delete a class (based off of its list number, given by another choice) which then deletes that class and then moves all the others up in the array. So, I want to be able to do that, and I'd presume that I'd have to use something along the lines of:

if(answer == 1 && classes[(answer - 1)] != NULL)
    {
      int classnum = answer - 1;
      free(classes[classnum]);
      classes[classnum] = (class_t*) malloc(sizeof(class_t));
      while(classnum <= MAX_CLASSES)
      {
        classes[classnum] = classes[(classnum + 1)];
        classnum++;
      }
    }

which works (from what i can tell) when there is something that's being pointed to, but how do i get it to not try to free anything when there isn't anything there. I thought that was what the classes[(answer -1)] != NULL did, but when I test it on a number that doesn't have anything pointing to, it gives me the error "munmap_chunk: invalid pointer."

I guess what I'm trying to ask is, how do I check if there isn't a class in that spot of the array, and effectively get rid of the error?

  • 1
    Possible duplicate of [Testing pointers for validity (C/C++)](https://stackoverflow.com/questions/551069/testing-pointers-for-validity-c-c) – Joseph Sible-Reinstate Monica Oct 18 '19 at 03:22
  • It is OK to free(NULL) - this will not crash your code. However, take a look at the while loop - you assign new malloc to classes[classnum], and then your "throw it way", when the loop assign classes[classnum+1] to classes[classnum]. What is the purpose of the while loop ? – dash-o Oct 18 '19 at 05:45
  • The while loop moves everything up. And it's in a while loop so it doesn't try to do it when there's no more array parts. – coltonious Oct 18 '19 at 14:05

0 Answers0