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;
}