0

I am trying to receive and save file over 5gb size using c++. But during the course of the process, memory used by the application is increasing and sometimes the application crashes. Is there something I am doing wrong ? Or is there a better way to do this?

    char * buffer = channel->cread(&len);
    __int64_t lengthFile = *(__int64_t * ) buffer;
    __int64_t received = 0;
    __int64_t offset = 0;
    __int64_t length;
    string filename = "received/testFile";
    ofstream ifs;
    ifs.open(filename.c_str(),ios::binary | ios::out);
    int len = 0;

    while(1){
        length = 256;
        if(offset + MAX_MESSAGE >= lengthFile){
            length = lengthFile - offset;
            breakCondition = true;
        }

        file = new filemsg(offset,length);
        channel->cwrite((char *)file,sizeof (*file));

        buffer = channel->cread(&len);
        ifs.write(buffer,length);
        received = received + length;
        offset = offset + MAX_MESSAGE;

        if(breakCondition)
            break;
    }
Som
  • 185
  • 15
  • 3
    Well you are repeatedly allocating a `filemsg` object without ever deleteing it – john Feb 15 '19 at 14:24
  • 2
    Please provide a [mcve] but basically you never `delete` `file`, you need to `delete` everything created with `new` or even better use `std::shared_ptr` or `std::unique_ptr` instead. In this case you can presumably avoid allocating anything and just declare file on the stack. – Alan Birtles Feb 15 '19 at 14:25
  • 3
    Any reason not to do the following? `filemsg file(offset,length); channel->cwrite((char *)&file,sizeof (file));` No allocation is needed. – john Feb 15 '19 at 14:25
  • What is `filemsg`? is that a POD type? – drescherjm Feb 15 '19 at 14:27
  • No its a simple class – Som Feb 15 '19 at 14:31
  • `len` is undefined – stark Feb 15 '19 at 14:31
  • ***No its a simple class*** Does it have any pointers or any objects like a `std::string`? If it does you can't use it that way. Here is info on POD types: https://stackoverflow.com/questions/146452/what-are-pod-types-in-c – drescherjm Feb 15 '19 at 14:37
  • Here is a link with examples: http://www.drdobbs.com/c-made-easier-plain-old-data/184401508 – drescherjm Feb 15 '19 at 14:46

0 Answers0