小编Jan*_*ona的帖子

在子进程中使用std :: string时出现C++内存泄漏

我对这段代码有问题,valgrind检测到std :: basic_string中的内存泄漏,我不知道我做错了什么.只有在子进程中使用std :: string时才会泄漏.你能告诉我,问题在哪里吗?我之前从未在C++中使用过fork(),因此我没有太多的经验.

#include <iostream>
#include <string>
#include <cerrno>
#include <cstdio>
#include <cstdlib>
#include <unistd.h>
#include <sys/wait.h>

int main(int argc, char *argv[])
{
    pid_t childPid = fork();
    if (childPid == -1)
    {
      perror("fork");
      return EXIT_FAILURE;
    }
    else if (childPid == 0)
    {
      std::cout << "Child PID: " << getpid() << std::endl;
      std::string str("something");      //valgrind detects mem leak here
      _Exit(EXIT_SUCCESS);
    }
    else
    {
      //std::string str("something");    //but not here
    }

    waitpid(-1, 0, 0);
  return EXIT_SUCCESS;
}
Run Code Online (Sandbox Code Playgroud)

c++ string memory-leaks fork

3
推荐指数
1
解决办法
368
查看次数

标签 统计

c++ ×1

fork ×1

memory-leaks ×1

string ×1