问题描述:

This is my code:

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

}

It is simply read one file, and print its content to screen.

In the function fileread, I use new std::string(buff); to get a std::string *, and return the point back. Will it cause memory leak? And if the answer is 'yes' , how to avoid it?


About use C in C++: fread is much faster than ifstream (tested with 1 billion random number)

My problem is about memory leak.

网友答案:

Return std::string by value. Don't worry, C++ will take care of not copying the object redundantly (unless you have a very old compiler). Here is the code, fixed:

#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;
}

I made only the small change necessary and ignored any other problems you might have in your code. Take care.

网友答案:

As Nawaz rightly commented: "DONT code C in C++. Use std::ifstream and std::string (not std::string*)". Here is the code in C++ to avoid all the issues:

#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;
}
相关阅读:
Top