在函数内返回指针值后如何删除指针

在函数内返回指针值后如何删除指针

本文介绍了在函数内返回指针值后如何删除指针的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这个功能:

char* ReadBlock(fstream& stream, int size)
{
    char* memblock;
    memblock = new char[size];
    stream.read(memblock, size);
    return(memblock);
}

每次我必须从文件中读取字节时,都会调用该函数.我认为每次使用它都会分配新的内存,但是一旦处理完数组中的数据,如何释放内存?我可以从功能外部执行此操作吗?通过分配大块来处理数据比分配和删除小块数据能提供更好的性能?

The function is called every time I have to read bytes from a file. I think it allocates new memory every time I use it but how can I free the memory once I have processed the data inside the array? Can I do it from outside the function? Processing data by allocating big blocks gives better performance than allocating and deleting small blocks of data?

非常感谢您的帮助!

推荐答案

使用delete[]释放动态数组:

char* block = ReadBlock(...);
// ... do stuff
delete[] block;

理想情况下,您在此处不使用手动内存管理:

Ideally however you don't use manual memory management here:

std::vector<char> ReadBlock(std::fstream& stream, int size) {
    std::vector<char> memblock(size);
    stream.read(&memblock[0], size);
    return memblock;
}

这篇关于在函数内返回指针值后如何删除指针的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-20 11:14