直到最近我一直都不需要一起使用strdup(stringp),strsep(&stringp_copy, token)我认为这会导致内存泄漏.
(strdup()以前总是free很好.)
我修复了泄漏,我想我明白了,但我无法弄明白为什么需要.
原始代码(摘要):
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);
Run Code Online (Sandbox Code Playgroud)
不泄漏的新代码:
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); …Run Code Online (Sandbox Code Playgroud)