Dynamic Memory

Greetings,
when programming I usually use C as opposed to C++, & when using dynamic memory use malloc & such functions seem a bit much code when I could be using C++'s new & delete, I know how to use these C++ alternatives in very simple examples, but if I wanted to replace malloc in the following code with new (& maybe put a delete at the end), what would I do? I cannot seem to get it to work myself.
Many thanks in advance.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
#include <stdlib.h>
#include <stdio.h>
int main()
{
  FILE* file=fopen("file.ext","rb");
  fseek(file,0,SEEK_END);
  size_t size=ftell(file);
  rewind(file);
  // -------------------------------------------
  char* buffer=(char*)malloc(sizeof(char)*size);
  // -------------------------------------------
  size_t result=fread(buffer,1,size,file);
  fclose(file);
  return 0;
}
1
2
3
char* buffer = new char[size];

delete[] buffer;
I know it's not what you asked, but even easier at that point is to use a vector to manage the memory for you:

1
2
3
4
5
6
size_t size = ftell( file );
rewind( file );
std::vector<char> buffer( size );
fread( &buffer[ 0 ], 1, size, file );
fclose( file );
return 0;

Great! That helps thanks to both.
Topic archived. No new replies allowed.