0

I have this code:

MountedJob* new_MountedJob(Job** job){
    MountedJob* new = malloc(sizeof(MountedJob*));
    printf("ok ");
    new->job = *job;
    printf("not ok");
    new->neededTools = new->job->toolSet;
    new->baseInstance = new->job->baseInstance;
    new->cj = new->baseInstance->C - hashset_size(new->neededTools);
    hashset_new(&new->unneededTools);
    return new;
}

It is executed 10 times, each time for a Job passed as an argument. They come from a iterated list and are generated exactly the same way. At the 3rd iteration, new->job = *job; crashes with access violation error code (0xc0000005). The problem is that it works just fine in debug mode so I have no clue what the problem could be. Especially that it works for the 2 first iterations, that's unconsistent I really don't understand.

Thank you.

Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343
Henri.D
  • 145
  • 9

2 Answers2

3

You are not allocating the proper size:

MountedJob* new = malloc(sizeof(MountedJob));

Otherwise, you only allocated one pointer, instead of a whole structure.

Matthieu Brucher
  • 21,634
  • 7
  • 38
  • 62
2

You are allocated memory of sizeof(MountedJob*) ie: a pointer size NOT the size of the structure, so then when accessing it, it is likely overwriting places it should not be.

It should be

MountedJob* new = malloc(sizeof(MountedJob));
lostbard
  • 5,065
  • 1
  • 15
  • 17