0

Is there any way i can delete the partial memory of the pointer.? for example

char *c = new char[1000];
sprintf(c,"this is it");

As it can be seen a lot of memory is getting wasted here. can I free the memory more than the required.?

AnT stands with Russia
  • 312,472
  • 42
  • 525
  • 765
user649558
  • 57
  • 5
  • 2
    Short answer: No. Why not just use `std::string`? If you really need to, you can use `malloc()` and `realloc()`. – Mysticial Aug 19 '12 at 00:08

3 Answers3

1

Not directly. The best you can do in C++ is to make a new copy that's the right size and delete the old one. There's no analog of C's realloc.

Pete Becker
  • 74,985
  • 8
  • 76
  • 165
0

Unless your system is a RAM-restricted embedded system, why bother? Just use ginormous buffers and include a 'dataLen' int.

Martin James
  • 24,453
  • 3
  • 36
  • 60
0

Well, allocate another memory block with the precise size required for the data, copy the data there and free the original (exceedingly large) memory block. Done.

AnT stands with Russia
  • 312,472
  • 42
  • 525
  • 765