copy strings into an arbitrary location !

A

alkhoudri

Hello everybody,

I am working on a project which contains in one of its files a code
like the following :

char * CurrentString = "\0";

void function01()
{
...
strcpy(CurrentString, "aString");
...
}

And the application doesn't crash !!!
Do you have any idea why ?
For me, it's just out of the question to copy a string in an
unallocated space (pointed to by CurrentString in the above example).

For info, the compiler is CodeWarior for an embedded system.
Thank you in advance.
 
M

mlimber

alkhoudri said:
Hello everybody,

I am working on a project which contains in one of its files a code
like the following :

char * CurrentString = "\0";

void function01()
{
...
strcpy(CurrentString, "aString");
...
}

And the application doesn't crash !!!
Do you have any idea why ?
For me, it's just out of the question to copy a string in an
unallocated space (pointed to by CurrentString in the above example).

You got lucky. What you've done is invoked undefined behavior, which
might mean a crash or subtle corruption of your other data or the end
of life on earth. It's *really* undefined, and you shouldn't do it for
that reason. Moreover, you should use std::string if you can (yes, I
know you're on an embedded system, but so am I; lots of embedded
environments can thrive with the standard library). At the very least,
you should use the safer strncpy.

Cheers! --M
 
F

Frederick Gotham

alkhoudri posted:
char * CurrentString = "\0";


It's illegal to alter a string literal; in light of this, it's best to use:

char const *CurrentString = "\0";

void function01()
{
...
strcpy(CurrentString, "aString");
...
}

And the application doesn't crash !!!
Do you have any idea why ?


You're writing to memory which isn't yours to write to. Either of these
things will happen:

(1) The system will deny the request and continue on.
(2) The system will deny the request and terminate the program.
(3) The system will allow the request and continue on.
(4) The system will allow the request and the program will crash.
(5) Internet Explorer will be launched and it will go to
www.howstuffworks.com.


Bottom line: Undefined Behaviour.

For me, it's just out of the question to copy a string in an
unallocated space (pointed to by CurrentString in the above example).


The Standard agrees.
 
A

alkhoudri

I wasn't excepting such detailed answers.
Thank you very much all.


Frederick Gotham a écrit :
 

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,744
Messages
2,569,483
Members
44,902
Latest member
Elena68X5

Latest Threads

Top