In my program I have a few malloc and realloc calls but for some reason when I call free on the ones that I called it still points to them as having direct leaks.
The variable name was declared earlier as char **names and wasn't initialized until below. I reallocating and allocating names under different parameters so I am not sure how to free that at the end. Would I just iterate through the entire names array once? Or do I have to do it multiple times?
names = malloc(size * sizeof(char *)); //MALLOC
names[0] = malloc(2 * sizeof(char)); //MALLOC
names[0] = "0\0";
names[1] = malloc(2 * sizeof(char)); //MALLOC
names[1] = "1\0";
int i;
for (i = 0; i < icount; i++) {
names[i + 2] = malloc(17 * sizeof(char)); //MALLOC
fscanf(file, "%*[: ]%16s", names[i + 2]);
}
names = realloc(names, size * sizeof(char *)); //REALLOC
for (i = 0; i < ocount; i++) {
names[i + icount + 2] = malloc(17 * sizeof(char)); //MALLOC
fscanf(file, "%*[: ]%16s", names[i + icount + 2]);
}
for (i = 0; i < numOutputs; i++) {
fscanf(file, "%*[: ]%16s", v);
int idx = indexOf(size, names, v);
if (idx == -1) {
size++;
tcount++;
names = realloc(names, size * sizeof(char *)); //REALLOC
names[size - 1] = malloc(17 * sizeof(char)); //MALLOC
strcpy(names[size - 1], v);
step.outputs[i] = size - 1;
}
if (!steps) {
steps = malloc(sizeof(struct directive)); //MALLOC
} else {
steps = realloc(steps, scount * sizeof(struct directive)); //REALLOC
}
You have a memory leak here:
names[0] = malloc(2 * sizeof(char)); //MALLOC
names[0] = "0\0";
names[1] = malloc(2 * sizeof(char)); //MALLOC
names[1] = "1\0";
You allocate space and assign a pointer to that space to names[0]
, then you immediately overwrite the pointer to the allocated space with a pointer to a string constant. names[1]
has the same problem.
Use strcpy
instead to copy the string into the allocated memory:
names[0] = malloc(2 * sizeof(char)); //MALLOC
strcpy(names[0], "0");
names[1] = malloc(2 * sizeof(char)); //MALLOC
strcpy(names[1], "1");
Note also that string constants are implicitly null terminated, so there's no need to add it manually.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.