I never had to use strdup(stringp) with strsep(&stringp_copy, token) together until recently, and I think this was causing a memory leak.
( strdup() always strdup() just fine before.)
I fixed the leak and I think I understand how, but I just canβt understand why I need it.
Source code (debriefing):
const char *message = "From: username\nMessage: basic message\n"; char *message_copy, *line, *field_name; int colon_position; message_copy = strdup(message); while(line = strsep(&message_copy, "\n")) { printf(line); char *colon = strchr(line, ':'); if (colon != NULL) { colon_position = colon - line; strncpy(field_name, line, colon_position); printf("%s\n", field_name); } } free(message_copy);
New code that does not leak:
const char *message = "From: username\nMessage: basic message\n"; char *message_copy, *freeable_message_copy, *line, *field_name; int colon_position; freeable_message_copy = message_copy = strdup(message); while(line = strsep(&message_copy, "\n")) { printf(line); char *colon = strchr(line, ':'); if (colon != NULL) { colon_position = colon - line; strncpy(field_name, line, colon_position); printf("%s\n", field_name); } } free(freeable_message_copy);
How is the message_copy pointer rewritten in the first code? or that?
source share