Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Have I succesfully removed the pointer from the heap?

Tags:

c++

file

The following code shows me getting the filesize of a certain file to then later on make a large enough buffer to ensure I can store all the files content in this buffer. So what I did was allocating it on the heap, because I couldn't know if the file is huge or not etc.

#include <iostream>
#include <string>
#include <cstdio>
#include <cstdlib>

size_t filesize(FILE* f) {
    size_t size;
    fseek(f, 0L, SEEK_END);
    size = ftell(f);
    fseek(f, 0L, SEEK_SET);

    return size;
}

char* read_file(std::string name) {
    FILE* f;
    fopen_s(&f, name.c_str(), "rb");
    size_t size = filesize(f);
    char* buffer = new char[size+1];

    memset(buffer, 0, size+1);

    fread(buffer, sizeof(char), size+1, f);
    fclose(f);

    return buffer; //this is the buffer with the content to send
}

int main() {
    char* buffer = read_file("main.cpp");

    printf("%s", buffer);

    delete[] buffer;
    buffer = nullptr;
    getchar();
    return 0;
}

My question is, have I successfully deleted

char* buffer = new char[size+1];

from the heap by doing this:

char* buffer = read_file("main.cpp");
delete[] buffer;
buffer = nullptr;

Or does it still remain somewhere? And if it does, how would I pin-point it and delete it?

Any other tips on how to handle raw pointers are appreciated as well.

like image 748
ye546 Avatar asked Nov 29 '25 10:11

ye546


1 Answers

Yes your code is correctly deleting the buffer.

C++ has various ways to handle this for you though so you don't need to worry about it and will be less likely to make mistakes and forget to free the buffer in some or all code paths, e.g. its easy to make mistakes like this:

int main()
{
  char* buffer = read_file("main.cpp");
  if ( buffer[0] != 'A' )
  {
     std::cout << "data is invalid\n";
     return 1; // oops forgot to free buffer
  }
  delete[] buffer;
  // data is valid
  return 0;
}

One option is to use std::unique_ptr which will free the buffer for you when it goes out of scope:

#include <memory>
#include <string>
#include <iostream>

std::unique_ptr<char[]> read_file(std::string name) {
    ....
    std::unique_ptr<char[]> buffer(new char[size+1]);
    ....
    return buffer;
}

int main()
{
  std::unique_ptr<char[]> buffer = read_file("main.cpp");
  if ( buffer[0] != 'A' )
  {
     std::cout << "data is invalid\n";
     return 1; // buffer is freed automatically
  }
  buffer.reset(); // can manually free if we are finished with buffer before it goes out of scope
  // data is valid
  return 0;
}
like image 74
Alan Birtles Avatar answered Dec 02 '25 00:12

Alan Birtles



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!