简体   繁体   English

C ++可能的内存泄漏读取文件

[英]C++ possible memory leak reading file

I'm relatively new to C++ and I'm trying to read a proprietary file format. 我是C ++的新手,我正在尝试阅读专有的文件格式。 I know the header format, and I've created a struct RTIHeader with the necessary fields. 我知道标题格式,并且我已经创建了一个包含必要字段的结构RTIHeader

My test code reads bytes from the file and copies them into the same memory space as the header struct, effectively reconstituting it. 我的测试代码从文件中读取字节并将它们复制到与头结构相同的内存空间中,从而有效地重新构造它。 My problem is that every time I run the test code (just calling the constructor) I get a different value! 我的问题是,每次运行测试代码(只是调用构造函数)时,我都会获得不同的值! My theory is that I do not fully understand memcpy . 我的理论是我不完全理解memcpy

struct RTIHeader decode(char* memblock){
    struct RTIHeader header;
    memcpy(&header,&memblock,sizeof(RTIHeader));
    return header;
}

RTIFile::RTIFile(const char* filename){
    // open the file in binary input mode with the pointer at the end
    std::ifstream file(filename,
                       std::ios::in |
                       std::ios::binary |
                       std::ios::ate);

    std::ifstream::pos_type size;
    char * memblock;
    RTIHeader header;

    // if the file didn't open, throw an error
    if(!file.is_open()){
        //TODO learn about C++ error handling
        return;
    }
    // use pointer position to determine file size
    size = file.tellg();
    // read file
    memblock = new char [sizeof(RTIHeader)];
    file.seekg(0,std::ios::beg);
    file.read(memblock,sizeof(RTIHeader));

    header = decode(memblock);

    std::cout << (unsigned int)header.signature[0] << "\n";

    // still need to read the rest of the file
    file.close();
}

You are passing the address of memblock as the second argument of memcpy . 您将memblock地址作为memcpy的第二个参数传递。 Since memblock is a parameter to the function, you will just be copying chunks of memory off your stack. 由于memblock是函数的参数,因此您只需从堆栈中复制内存块。

To fix, just pass the pointer directly: 要修复,只需直接传递指针:

memcpy(&header,memblock,sizeof(RTIHeader));

By the way, since you are returning the structure by value, you will incur an extra memcpy as the returned value is copied in full (unless your compiler optimizes it). 顺便说一下,由于您按值返回结构,因此返回值将被完全复制(除非编译器对其进行优化),否则将产生额外的 memcpy。 To avoid this, you should consider passing the target structure as a pointer to decode , as in 为避免这种情况,您应该考虑将目标结构作为指向decode的指针传递,如

struct RTIHeader *decode(struct RTIHeader *header, char* memblock){
    memcpy(header, memblock, sizeof(RTIHeader));
    return header;
}

Then you just have to do 然后你就必须这样做

decode(&header, memblock);

which is more efficient. 哪个更有效率。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM