When I allocate memory for array in C, I try to use Malloc and just use 1 byte.
str = (char *) malloc(1);
after that I copy a string "How the memory works"
to str
.
So surprise then str
can save How the memory works
. Before I run the program I guess this will be overflow memory :( . Can you explain why str
can store data more than 1 byte? May the program auto realloc
?
Asked
Active
Viewed 32 times
0

Stack
- 111
- 6
-
5Writing to invalid memory is undefined behaviour. UB means it may appear to "work", or it may crash, or it may produce wrong results or any other behaviour. – kaylum May 29 '20 at 04:21
-
What makes you think you did not overflow the allocated memory? – John Bollinger May 29 '20 at 04:24
-
I think it will be an overflow memory. But I don't understand why "How the memory works" can store or I lucky when it works – Stack May 29 '20 at 04:28
-
`malloc` returns a memory address. The memory is a huge collection of bytes that are accessible by address. It's like checking into a hotel, asking for 3 consecutive rooms. You get the keys to rooms 503, 504 and 505. So you go the fifth floor, and are surprised that there is a hallway with at least twenty rooms. If you try to go into room 506, you may or may not succeed, you may walk into a naked guest, you may get thrown out. – Cheatah May 29 '20 at 21:31