1

Let's say we have this code which reads in 10 space separated strings in a file and prints them all out. When running the code, I get a "heap-use-after-free" error. First, I tried removing LINE A. Doing so gave me a "attempting free on address which was not malloc()-ed" error. Next, I tried removing LINE B and re-adding LINE A. Doing so gave me a "detected memory leaks" error. I feel like I'm in a bit of a bind here. How do I properly free everything? (both the "pointer array" of structs and the character "pointer arrays" inside of each struct)

#include <math.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

typedef struct strs {
    char* s;
} str;

int main(int argc, char* argv[argc + 1]) {
    FILE* fp = fopen(argv[1], "r");
    
    //Malloc
    str* ex = (str*)malloc(10 * sizeof(str));
    for (int a = 0; a < 10; a++) {
        (ex+a)->s = (char*)malloc(sizeof(char) * 10);
    }

    //Scan
    for (int a = 0; a < 10; a++) {
        fscanf(fp, "%s ", (ex+a)->s);
    }

    //Print
    for (int a = 0; a < 10; a++) {
        printf("%s ", (ex+a)->s);
    }

    //Free
    for (int a = 0; a < 10; a++) {
        free((ex+a)->s); //LINE A
        free(ex+a); //LINE B
    }

    printf("\n");
    return 0;
}

1 Answer 1

4

The number of calls to free should be equal to the number of calls to malloc, and what is passed to free should be exactly the same as what was returned from malloc.

str* ex = (str*)malloc(10 * sizeof(str));
for (int a = 0; a < 10; a++) {
    (ex+a)->s = (char*)malloc(sizeof(char) * 10);
}

Here you call malloc once for the array of str, then 10 more times for the s member in each array member.

for (int a = 0; a < 10; a++) {
    free((ex+a)->s); //LINE A
    free(ex+a); //LINE B
}

The first line inside of the loop is fine. The second one is not because ex+a was not a value returned from malloc (except for the first iteration).

You need to free the s members inside of the loop, then you free the array after the loop.

for (int a = 0; a < 10; a++) {
    free((ex+a)->s);
}
free(ex);
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.