Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Strcpy a bigger string to a smaller array of char

Tags:

c

Why when I do this:

char teststrcpy[5];

strcpy(teststrcpy,"thisisahugestring");

I get this message in run time:

Abort trap: 6

Shouldn't it just overwrite what is in the right of the memory of teststrcpy? If not, what does Abort trap means?

I'm using the GCC compiler under MAC OSX

As a note, and in answer to some comments, I am doing this for playing around C, I'm not going to try to do this in production. Don't you worry folkz! :)

Thanks

like image 664
Nobita Avatar asked Jan 22 '13 19:01

Nobita


2 Answers

I don't own one, but I've read that Mac OS treats overflow differently, it won't allow you to overwrite memory incertian instances. strcpy() being one of them

On Linux machine, this code successfully overwrite next stack, but prevented on mac os (Abort trap) due to a stack canary.

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


Ok, since you're seeing an abort from __strcpy_chk that would mean it's specifically checking strcpy (and probably friends). So in theory you could do the following*:

char teststrcpy[5];
gets(teststrcpy);

Then enter your really long string and it should behave baddly as you wish.

*I am only advising gets in this specific instance in an attempt to get around the OS's protection mechanisms that are in place. Under NO other instances would I suggest anyone use the code. gets is not safe.

like image 181
Mike Avatar answered Oct 01 '22 22:10

Mike


Shouldn't it just overwrite what is in the right of the memory of teststrcpy?

Not necessarily, it's undefined behaviour to write outside the allocated memory. In your case, something detected the out-of-bounds write and aborted the programme.

like image 44
Daniel Fischer Avatar answered Oct 01 '22 22:10

Daniel Fischer