I'm trying to use the strdup() function in C but I'm getting an odd error involving malloc. My condensed code is:
void loadEntity(FILE *inFP, entity_t *ent, char *token) {
char buffer[100] = "buffer";
if (strcmp(token, "name") == 0) {
if (fscanf(inFP, "%s", buffer) != 1) {
fprintf(stderr,"%s\n", "Error reading name.");
exit(1);
}
//For testing purposes
fprintf(stdout, "Buffer: %s", buffer);
ent -> name = strdup(buffer);
}
}
And the result is:
hw6: malloc.c:2451: sYSMALLOc: Assertion `(old_top == (((mbinptr) (((char *) &((av)->bins[((1) - 1) * 2])) - __builtin_offsetof (struct malloc_chunk, fd)))) && old_size == 0) || ((unsigned long) (old_size) >= (unsigned long)((((__builtin_offsetof (struct malloc_chunk, fd_nextsize))+((2 * (sizeof(size_t))) - 1)) & ~((2 * (sizeof(size_t))) - 1))) && ((old_top)->size & 0x1) && ((unsigned long)old_end & pagemask) == 0)' failed.
Buffer: plane1Aborted (core dumped)
Towards the very end of the result, you can see the result of my fprintf statement (Buffer: plane1), which is exactly as it should be. The first line of my input text is "name plane1". So basically, it's seeing the token name, taking the next word, and then setting ent -> name to this. Seems simple but it's not working. Note that even if I remove the if statements, it has the same result. Also, if I just make it "strdup("String")", I get the same problem.
Also, if I just make it "strdup("String")", I get the same problem.
I think memory is corrupted somewhere else, you should use valgrind or something else to detect memory leaks, and go from there.