C qsort fn segementation fault

  Kiến thức lập trình

I have the following comparison function:

  int compareByMemSize(const void *a, const void *b)
      const struct ProcInfo *procInfo1 = (const struct ProcInfo *) a;
      const struct ProcInfo *procInfo2 = (const struct ProcInfo *) b;
      if (( procInfo1->memSize != NULL && procInfo1->memSize[0] != '' ) && ( procInfo2->memSize != NULL && procInfo2->memSize[0] != '' ))
          long memSize1 = strtol(procInfo1->memSize, NULL, 10);
          long memSize2 = strtol(procInfo2->memSize, NULL, 10);
          if (memSize1 < memSize2)
              return -1;
          if (memSize1 > memSize2)
              return 1;
          return 0;
      if (procInfo1->memSize == NULL && procInfo2->memSize == NULL)
          return 0;
      if (procInfo1->memSize == NULL)
          return -1;
      return 1;

that does comparison logic for the following struct:

  typedef struct ProcInfo {                                                                                                                                                                   
      int  PID;
      char *name;
      char *memSize;
  } ProcInfo;

and I make the qsort call like so:

qsort(&a, sizeof(a), sizeof(ProcInfo), compareByMemSize);    

where a is of type of ProcArray:

typedef struct ProcArray {                                                                                                                                                                    
    ProcInfo *array;
    size_t used;
    size_t size;
} ProcArray;

the result is a seg fault and I think it’s due to the fact that memSize could either be a long char arr, for example: 122313131 (it’s a char[] because it originally contains a ‘kB’ and I took out the ‘kB’ for the comparison) or a ”.

Some memSize values originally also don’t exist and so I compensated by setting their char[] to ”, hence the check for that char above.

Am I just using qsort wrong? or is my approach to setting a char[] to ” if the value isn’t found wrong?

If more code is needed, I’ll be more than happy to provide!