Reputation: 57
I'm trying to write a parser to import OBJ files, but even at this early stage I am experiencing the following error on execution:
malloc: Incorrect checksum for freed object 0x7fd4f4c8bbd0: probably modified after being freed.
It manages to print the buffer size each line, so I'm wondering if the issue is connected to closing the file after the operation.
Could somebody tell me what I'm doing wrong? I'm running on macOS.
int Utilities_Import_OBJ(const char *filename) {
// input checking
if (filename == NULL) {
printf("Unable to parse file, filename was NULL.\n");
return -1;
}
char *path = strcat(_resource_path, filename);
FILE *file = fopen(path, "r");
if (file == NULL) {
printf("Error opening %s\n", filename);
return -1;
}
// create a line buffer
const int length = 1024;
char buffer[length];
int index = 0;
// fgets stops reading at a \n and appends \0
while (fgets(buffer, sizeof(buffer), file)) {
printf("Buffer size at line %d : %d\n", index, sizeof(buffer));
index++;
}
// done with file, so close it
if (fclose(file) != 0) {
printf("Failed to close file!\n");
return -1;
}
return 0;
}
Upvotes: 1
Views: 1229
Reputation: 144951
There are 2 surprising lines in your code:
char *path = strcat(_resource_path, filename);
strcat
does not concatenate 2 strings into a third allocated one. It copies the second string at the end of the first. Depending on how _resource_path
is allocated, it is quite possible that this very line corrupt the malloc()
internal data and ultimately produces the problem. You should write a specific function like this:
char *concat(const char *s1, const char *s2) {
size_t len1 = strlen(s1);
size_t len2 = strlen(s2);
char *p = malloc(len1 + len2 + 1);
if (p) {
memcpy(p, s1, len1);
memcpy(p + len1, s2, len2 + 1);
}
return p;
}
And you would free
the string returned by char *path = concat(_resource_path, filename);
after use.
printf("Buffer size at line %d : %d\n", index, sizeof(buffer));
The buffer size is constant, sizeof(buffer)
always evaluates to the value length
had at the point buffer
was defined (1024). Furthermore, you should use %zu
for a size_t
argument, not %d
, which expects an int
, that may have a different size. You might want to write this instead:
printf("Buffer length at line %d: %zu\n", index, strlen(buffer));
Upvotes: 1