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.