By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
449,168 Members | 1,178 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 449,168 IT Pros & Developers. It's quick & easy.

Wierd Behaviour: Crash at 'delete' of memory.

P: n/a
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

Jul 23 '05 #1
Share this Question
Share on Google+
3 Replies


P: n/a
PSN wrote:
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
Jul 23 '05 #2

P: n/a
"PSN" <pr********@gmail.com> wrote in message
news:11**********************@g14g2000cwa.googlegr oups.com...
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
Jul 23 '05 #3

P: n/a
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

Jul 23 '05 #4

This discussion thread is closed

Replies have been disabled for this discussion.