mercredi 8 février 2017

Segmentation fault, if code is in external compiled file but not if in same file as main?

Vote count: 0

I'm attempting to implement a malloc with segregated lists and I'm having difficulties debugging this part of my program. This is just part of the program, do tell if I should post more.

Weird thing is that if I pull all the code out from my my_malloc.c (which I would otherwise compile to an object file, *.o) and paste the content into a regular *.c file (test.c) with a main, I can run the malloc code, and it seems to work. But if I keep it in the external file and compile it as

gcc -o test my_malloc.o test.c -lm

and then call malloc in test.c it doesn't work.

It seems like it is the last line of this code which is the cause, commenting out the line makes the error go away (but of course give me no output so it doesn't really help), but I can't figure out why.

Basically I'm calling this piece of code to find a list reference (in segElement) which holds the reference to a list of empty memory blocks.

typedef struct chunk {
  int size;
  int length;
  int new;
  struct chunk *next; // pointer to the next element in a list
} chunk;

typedef struct seg {
  long size;
  struct chunk *cnkHead;
  struct seg *next;
} seg;

seg *getNewSegElement(long size, seg *next, seg *prev) {
  // ask kernel for space for new list
  void *memory = sbrk(sizeof(seg));

  // sbrk() will return -1 if we could not get space for new list
  // from the OS.
  if(memory == (void *) -1) {
    return NULL;
  } else {
    seg *sg = (seg*) memory;
    sg->next = NULL;
    sg->cnkHead = NULL;
    sg->size = size;

    // no segregation lists at all
    if (segList == NULL) {
      segList = sg;

      // no segregation lists of this size
      // and no larger
    } else if (next == NULL) {
      prev->next = sg;

      // no segregation list of this size
      // but next is larger
    } else {
      prev->next = sg;
      sg->next = next;
    }

    return sg; 
  }
}

seg *getSegElement(long size) {
  //size_t size = size_;
  seg *next = segList;
  seg *prev = NULL;

  while(next != NULL) {
    if(next->size == size) {
      return next;
    } else if(next->size > size){
      break;
    } else {
      prev = next;
      next = next->next;
    }
  }
  return getNewSegElement(size, next, prev); // <-- seems to give weird seg fault.
}

asked 21 secs ago

Let's block ads! (Why?)



Segmentation fault, if code is in external compiled file but not if in same file as main?

Aucun commentaire:

Enregistrer un commentaire