Link to home
Start Free TrialLog in
Avatar of TomG_london
TomG_london

asked on

Problem deallocating memory for pointer

I've written this really simple win32 console program in Visual C++ to take in a name and print it out on the screen but when I run it, though it works, it exits with a debug error and I can't figure out why - can anyone help?

The program is :


#include <iostream>

int main(void)
{
  char *name = new char;

  std::cout << "please enter your name/n ";
  std::cin >> name;
  std::cout << "hello " << name;

  delete name;
  return 0;
}

 
ASKER CERTIFIED SOLUTION
Avatar of Rimvis
Rimvis
Flag of Lithuania image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of nanden
nanden

you are allocating a char pointer and then deleting it is causing memory corruption since the size you are trying to delete is greater than the one allocated.
use char *name = new char[SOMESIZE]; where SOMESIZE is less than what you anticipate the user to enter for the name. Else, best you use CStrings.
HTH<
Avatar of TomG_london

ASKER

Thanks both, I will accept both your posts as answers but I have a further question, what is the advantage of dynamically allocating a pointer to an array over just declaring a an array of a certain size as in char[10] name?

The reason I was using the pointer was so there was no restriction on the length of name, is using the CStrings class the only way to get around this?

Thanks

Tom
what you are actually doing when you are getting a pointer and allocating data to it is getting memory on the heap. You got to know how much memory to deallocate when you are deleting and hence the "SOMESIZE" array that i was talking abt. What CStrings do is that they maintain the array internally and decide the size of the array depending on how much data the user wants it to hold. you can do the same using your pointer, then check the user input and allocate the same amount of memory to your pointer as the user inputted data needs. then it would be very similar to the way CStrings allocate memory. (except for the vast number of member funx that CStrings provide)
HTH.