即使在free()之后,strdup()内存泄漏 [英] strdup() memory leak even after free()

查看:359
本文介绍了即使在free()之后,strdup()内存泄漏的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

直到最近,我再也不需要将strdup(stringp)strsep(&stringp_copy, token)一起使用,并且我认为这会导致内存泄漏.

I've never needed to use strdup(stringp) with strsep(&stringp_copy, token) together until recently and I think it was causing a memory leak.

(strdup()以前总是free就可以了.)

(strdup() has always free'd just fine before.)

我修复了泄漏,我想我知道如何,但是我不知道为什么需要这样做.

I fixed the leak, and I think I understand how, but I just can't figure out why I needed to.

原始代码(摘要):

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);

不会泄漏的新代码:

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);

如何在第一个代码中覆盖message_copy指针?还是它?

How is the message_copy pointer being overwritten in the first code? or is it?

推荐答案

函数strsep()获取指向原始字符串(message_copy)的指针,并对其进行修改以返回指向'next'令牌的新指针

The function strsep() takes a pointer to the original string (message_copy) and modifies it to return a new pointer to the 'next' token

const char *message = "From: username\nMessage: basic message\n";
char *message_copy, *original_copy;
//here you have allocated new memory, a duplicate of message
message_copy = original_copy = strdup(message);

在此处打印出指针,

printf("copy %p, original %p\n", message_copy, original_copy);

请注意,当您使用strsep()时,您正在修改message_copy,

Note that as you use strsep(), you are modifying the message_copy,

char* token;
//here you modify message_copy
while(token = strsep(&message_copy, "\n")) {
    printf("%s\n", token);
}

这说明了已更改的message_copy,而original_copy不变,

This illustrates the changed message_copy, while original_copy is unchanged,

printf("copy %p, original %p\n", message_copy, original_copy);

由于message_copy没有指向原始的strdup()结果,所以这是错误的,

Since message_copy does not point to the original strdup() result this would be wrong,

free(message_copy);

但是请保留原始的strdup()结果,并且此免费软件有效

But keep around the original strdup() result, and this free works

//original_copy points to the results of strdup
free(original_copy);

这篇关于即使在free()之后,strdup()内存泄漏的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆