0

The error message is "incorrect checksum for freed object - object was probably modified after being freed."

This is the function that is giving me trouble. 'npart' and 'parts' are global variables. 'npart' is an int while 'parts' is an array of structs (see declaration below).

typedef struct {
    int bSites;
    int rotState; // Direction
    int pos[2]; // Array index and layer
} Molecule;

Molecule *parts;

Here, I cast the quotient to an int to truncate the decimal places.

void printXYZ() {

    fprintf(fp, "%d\n\n", npart);
    for (int i = 0; i < npart; i++){
        char type = ((int) xyz[i][0]) == 3 ? 'S' : 'O';

        double x, y, z;
        z = parts[i].pos[0];
        y = ((int) parts[i].pos[1] / size) * 1.73205080757 / 2.0;
        if (((int) parts[i].pos[1] / size) % 2 == 0)
            x = (double)(parts[i].pos[1] % size);
        else
            x = ((double)(parts[i].pos[1] % size)) / 2.0;
        printf("%c\t%f\t%f\t%f\n", type, x, y, z);
        fprintf(fp, "%c\t%f\t%f\t%f\n", type, x, y, z);
    }

}

I allocate memory for the 'parts' array and call the printXYZ() function in main:

parts = (Molecule*) malloc(npart * sizeof(Molecule));

Please help!

SpacemanSpiff
  • 223
  • 1
  • 2
  • 10
  • There's no need to put `(int)` before `parts[i].pos[1]`, since it's declared to be `int`. – Barmar Jun 06 '18 at 20:44
  • 4
    I don't see anything in this function that would cause that error. You probably have undefined behavior somewhere else in your program, and it's corrupting the heap. – Barmar Jun 06 '18 at 20:45
  • 3
    [don't cast malloc](http://stackoverflow.com/questions/605845/do-i-cast-the-result-of-malloc) – Barmar Jun 06 '18 at 20:45
  • That shouldn't fix anything. – Barmar Jun 06 '18 at 20:54
  • 2
    Where is the code that calls `free()`? – Jens Jun 06 '18 at 21:00
  • Yeah it fixed it for a second and then went back to error. I'm pretty new toC so I'm not sure what I need free() for. – SpacemanSpiff Jun 06 '18 at 21:17
  • Note: rather than `parts = (Molecule*) malloc(npart * sizeof(Molecule));`, consider `parts = malloc(sizeof *parts * npart);`. It is easier to code correctly, review and maintain. Not likely the cause of your present issue. A [mcve] would help. – chux - Reinstate Monica Jun 06 '18 at 22:11

0 Answers0