Can you tell me how can inv[1].ID be set up to 20. When I allocated just 1 byte of memory for inv. How can it carry data of multiple structures?
TL;DR It cannot.
What you're seeing is invalid access of memory which invokes undefined behavior. There is nothing in C standard that prevents you from from writing a code accessing invalid memory, but as soon as you do that, voila!!
The memory allocated to inv
(by calling malloc(1)
) is way less then it should be. Thus, basically, you're trying to access memory that does not belong to you (your process) and hence that memory is invalid. Any attempt to access invalid memory results in UB.
Following the same trail, even after you have allocated proper memory for inv
, then also
strcpy(inv[0].name,"hello charlie old mate");
will be UB, as you're trying to copy more than 20
elements into the destination having only size of 20 (which can hold 19 valid chars
+ 1 null terminator, if you want name
to be used as a string). Count your memory requirement properly and stay within bounds.
That said, always check for the return value of malloc()
for success before using the returned pointer.