Search code examples
cdynamic-allocationheap-corruption

Heap-corruption when freeing allocated memory


I am writing small school project, and I got stuck with error that I can't fix. When I try to free allocated memory, I get this error:

Heap Corruption Error

Here is the code that involves my char pointer temp:

1. Allocation of memory and setting starting value:

 char *temprijec(int rng, RIJEC *B, int *len) {
    int i;
    char *temp=(char*)calloc(*len + 1, sizeof(char));
    *len = strlen((B + rng)->rijec);
    for (i = 0; i < *len; i++) {
        if (i == 0) {
            temp[i] = (B + rng)->rijec[i];
        }
        else if (i == (*len)) {
            temp[i] = '\0';
        }
        else {
            temp[i] = '_';
        }
    }
    return temp;
 }

2. Working with char pointer temp:

void tijek_igre(char*temp,RIJEC *B,int rng,int len,int*br2pok,int *pokpogreska,int *pokbr,char*pokch) {
    int i;
    printf("\nPogodi slovo ili rijec!");
    *pokch = _getch();
    for (i = 0; (B + rng)->rijec[i] != '\0'; i++) {
        if (*pokch == (B + rng)->rijec[i]) {
            temp[i] = *pokch;
        }
    }
    for (i = 0; (B + rng)->rijec[i] != '\0'; i++) {
        if (*pokch != (B + rng)->rijec[i]) {
            (*br2pok)++;
            if (*br2pok == len) {
                (*pokpogreska)++;
            }
        }
    }
    for (i = 0; temp[i] != '\0'; i++) {
        if (temp[i] != '_') {
            (*pokbr)++;
        }
    }
}

Everything is fine until I try to free it with free(temp);


Solution

  • I fixed the error by changing the way I am passing variables to function,structure instead of pointers and now it works idk why but it works :).Tnx everyone for help.

    Changed code:

    VARIJABLE temprijec(VARIJABLE V, RIJEC *B) {
        int i;
        V.len = strlen((B + V.rng)->rijec);
        V.temp = (char*)calloc(V.len + 1, sizeof(char));
    
        for (i = 0; i < V.len + 1; i++) {
            if (i == 0) {
                V.temp[i] = (B + V.rng)->rijec[i];
            }
            else if (i == (V.len)) {
                V.temp[i] = '\0';
            }
            else {
                V.temp[i] = '_';
            }
        }
        return V;
    }
    

    and

    VARIJABLE tijek_igre(RIJEC *B, VARIJABLE V) {
        int i;
        printf("\nPogodi slovo ili rijec!");
        V.ch = _getch();
        for (i = 0; (B + V.rng)->rijec[i] != '\0'; i++) {
            if (V.ch == (B + V.rng)->rijec[i]) {
                V.temp[i] = V.ch;
            }
        }
        for (i = 0; (B + V.rng)->rijec[i] != '\0'; i++) {
            if (V.ch != (B + V.rng)->rijec[i]) {
                (V.pogresno_slovo)++;
                if (V.pogresno_slovo == V.len) {
                    (V.pogreska)++;
                }
            }
        }
        for (i = 0; V.temp[i] != '\0'; i++) {
            if (V.temp[i] != '_') {
                (V.tocno_slovo)++;
            }
        }
        return V;
    }