字符串内存分配中可能的内存泄漏

时间:2014-03-23 09:10:01

标签: c++ string memory-leaks stl

这是我的代码:

#include <string>
#include <iostream>

#include <cstdio>
#include <cstdlib>

std::string & fileread(const char * name)
{
    FILE *fp = fopen(name,"rb");
    size_t sz;
    int i;
    char *buff;
    fseek(fp, 0, SEEK_END);  
    sz = ftell(fp);
    fseek(fp, 0, SEEK_SET);
    buff = (char *)malloc(sizeof(char)*(sz+1));
    buff[sz] = '\0';
    fread(buff,sz,1,fp); 
    std::string * rtstr = new std::string(buff);
    free(buff);
    fclose(fp);
    return * rtstr;
}

int main(int argc,char * argv[])
{
    std::string file_info(fileread(argv[1]));
    std::cout<<file_info << std::endl;
    return 0;
}

只需读取一个文件,然后将其内容打印到屏幕上。

在函数fileread中,我使用new std::string(buff);获取std::string *,然后返回该点。它会导致内存泄漏吗?如果答案是'是',如何避免它?


关于在C ++中使用C:freadifstream快得多(用10亿随机数测试)

我的问题是内存泄漏。

2 个答案:

答案 0 :(得分:0)

正如Nawaz正确评论的那样:&#34;在C ++中没有代码C.使用std :: ifstream和std :: string(不是std :: string *)&#34;。以下是C ++中用于避免所有问题的代码:

#include <iostream>
#include <fstream>
#include <string>

using namespace std;

int main () {

  string line;
  ifstream myfile ("myfile.txt");

  if (myfile.is_open())
  {
    while ( getline (myfile,line) )
    {
      cout << line << '\n';
    }
    myfile.close();
  }

  else cout << "Unable to open file"; 

  return 0;
}

答案 1 :(得分:0)

按值返回std :: string。不用担心,C ++将负责不冗余地复制对象(除非你有一个非常旧的编译器)。 这是代码,修复:

#include <string>
#include <iostream>

#include <cstdio>
#include <cstdlib>

std::string fileread(const char * name)
{
    FILE *fp = fopen(name,"rb");
    size_t sz;
    int i;
    char *buff;
    fseek(fp, 0, SEEK_END);  
    sz = ftell(fp);
    fseek(fp, 0, SEEK_SET);
    buff = (char *)malloc(sizeof(char)*(sz+1));
    buff[sz] = '\0';
    fread(buff,sz,1,fp); 
    std::string rtstr(buff);
    free(buff);
    fclose(fp);
    return * rtstr;
}

int main(int argc,char * argv[])
{
    std::string file_info(fileread(argv[1]));
    std::cout<<file_info << std::endl;
    return 0;
}

我只进行了必要的小改动,忽略了代码中可能存在的任何其他问题。小心。

相关问题