Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

strcat() & strcpy() works even if enough memory is not allocated [duplicate]

Tags:

c

While implementing infix to postfix and vice versa algorithms

I found,

char * str = (char*) malloc(1);
strcpy(str,str2);

this works even if str2 is more than 1 characters(20 chars or more).

I did not get any warning or runtime error.

How is this possible?

Note:

I did not get garbage also.

I always get required result irrespective of str2.

like image 847
Abhimanbhau Avatar asked Dec 19 '22 18:12

Abhimanbhau


1 Answers

The reason this works is that C has unchecked memory access. strcpy/strcat have NO IDEA how much memory is at the other end of the pointer you gave them. They just assume you know what you are doing, and go for it.

As to why you didn't see a problem: Well, they wrote into that memory. There's nothing stopping them from writing beyond what you've allocated, so they do. So when you look at it later, it's fine. So what's going on? They wrote over something else!

Might be they wrote over something else that was already allocated, might be they wrote over unallocated space, might be that you got lucky and they wrote over something that nothing cares about.

Might be they wrote over internal structures, and some time later you'll get malloc crashing.

If you know that you've allocated enough buffer somehow, it's OK to use these functions, but in most cases (and especially if the thing being copied came from the user), you'll want to look at strncpy. But be careful that one has some other traps for the unwary.

like image 128
Michael Kohne Avatar answered Jan 02 '23 22:01

Michael Kohne