Strcpy add large string to smaller char array

Why when I do this:

char teststrcpy[5]; strcpy(teststrcpy,"thisisahugestring"); 

I get this message at runtime:

 Abort trap: 6 

Should I rewrite what is to the right of teststrcpy's memory? If not, what does the interrupt trap mean?

I am using the GCC compiler under MAC OSX

As a note, and in response to some comments, I am doing this for a game around C, I am not going to do this in production. Don’t worry, people! :)

thanks

+4
source share
5 answers

I don’t have it, but I read that Mac OS handles overflow differently, this will not allow you to overwrite incremental memory instances. strcpy() is one of them

On a Linux machine, this code successfully overwrites the next stack, but is prevented on mac os (interrupt interruption) due to the canary stack .

You might be able to get around this with the gcc -fno-stack-protector option


Good, since you see an interrupt from __strcpy_chk , which would mean its concrete check with strcpy (and probably friends). Therefore, theoretically you can do the following:

 char teststrcpy[5]; gets(teststrcpy); 

Then enter your very long line, and it should behave badly as you wish.

* I recommend only gets in this particular case, trying to get around the OS protection mechanisms that exist. In NO other cases, I would suggest anyone use the code. gets not safe.

+1
source

Shouldn't we just overwrite what is to the right of teststrcpy memory?

Not necessarily, this behavior is undefined for writing outside of allocated memory. In your case, something has discovered that external constraints write and interrupt the program.

+2
source

In C, there is no one to tell you that the “buffer is too small”, if you insist on copying too many characters into a too small buffer, you will go to undefined terror behavior

+2
source

If you enjoy rewriting what after the 5th char teststrcpy, you are a scary person. You can copy a line of size 4 into your test script (the fifth char SHOLULD is reserved for NULL).

0
source

Most likely, your compiler uses a canary to protect buffer overflows and thus throws this exception when an overflow occurs, which prevents writing outside the buffer.

See http://en.wikipedia.org/wiki/Buffer_overflow_protection#Canaries

0
source

All Articles