• + 1 comment

    Strange: I got rid of the sole call to realloc and performed the reallocation "manually", e.g. with a malloc, a free, and assignment to the new memory, and the segfaults went away. I'm not sure what the issue was, since it only segfaulted for two cases, and those two cases worked fine when I ran them on my local machine.

    Note that I allow package_count to be smaller than capacity, but the realloc was occurring only when the array of packages was full, so there shouldn't be any issue with unitialized elements. If anyone can explain why realloc was causing segfaults, but not a manual malloc and free, that would be great.

    void add_package(Office *o, Package p){
      if(o->package_count==o->capacity){
        o->capacity *= 2;
        Package *expanded = malloc(o->capacity*sizeof(Package));
        unsigned i=0;
        for(i=0; i<o->package_count; ++i){
          expanded[i] = o->packages[i];
        }
        free(o->packages);
        o->packages = expanded;
      }
      o->packages[o->package_count++] = p;
    }