Wierd Behaviour: Crash at 'delete' of memory.

P

PSN

Hi all ..

here is the code which crashes at the time of freeing the pointer
memory.

************************************
char *complete_command;
complete_command = new char[strlen(command) + strlen(" >> moto_msg")];

strcpy(complete_command, command);
strcat (complete_command, " >> moto_msg");

<SOME IRRELEVANT FUNCTIONS/CODE>

if (flag != 1)
ULTI_ERROR = -6;
delete [] complete_command; // CRASHES HERE
**************************************

Can someone explain me what am i doing wrong ??

Thanks and regards,
Prakash
 
V

Victor Bazarov

PSN said:
here is the code which crashes at the time of freeing the pointer
memory.

************************************
char *complete_command;
complete_command = new char[strlen(command) + strlen(" >> moto_msg")];

Add one to the number of allocated chars. You forget the terminator.
strcpy(complete_command, command);
strcat (complete_command, " >> moto_msg");

<SOME IRRELEVANT FUNCTIONS/CODE>

if (flag != 1)
ULTI_ERROR = -6;
delete [] complete_command; // CRASHES HERE
**************************************

Can someone explain me what am i doing wrong ??

V
 
M

Mike Wahler

PSN said:
Hi all ..

here is the code which crashes at the time of freeing the pointer
memory.

************************************
char *complete_command;
complete_command = new char[strlen(command) + strlen(" >> moto_msg")];

strcpy(complete_command, command);
strcat (complete_command, " >> moto_msg");

<SOME IRRELEVANT FUNCTIONS/CODE>

if (flag != 1)
ULTI_ERROR = -6;
delete [] complete_command; // CRASHES HERE
**************************************

Can someone explain me what am i doing wrong ??

You're writing past the end of your allocated memory.
After that, the behavior of 'delete[]' (and anything else
in your program) is undefined, so anything could happen.

Both 'strcpy()' and 'strcat()' append a terminator ('\0')
after they copy. You didn't provide enough storage for
both your strings and the terminator.

complete_command = new char[strlen(command) + strlen(" >> moto_msg") + 1];

You can eliminate all the headaches of managing your own string
memory by using the std::string type instead.

-Mike
 
P

PSN

Thank you both for your answers ..

ya, i just found out my mistake. it was very stupid. Anyway, thanks
again for your quick input.

Prakash
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,764
Messages
2,569,566
Members
45,041
Latest member
RomeoFarnh

Latest Threads

Top