array pointers to structures

I wrote this program:

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

struct inventory{
    int ID;
    char name[20];
    int value;
};


int main()
{
    struct inventory *inv;

    inv = malloc(sizeof(1));

    inv[0].ID = 10;
    strcpy(inv[0].name,"hello charlie old mate");
    inv[0].value = 20;

    inv[1].ID = 20;

    printf("%d", inv[1].ID);

    return 0;
   }

Can you tell me how caninv[1].IDbe set up to 20. When I allocated just 1 byte of memory forinv. How can it carry data of multiple structures?

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;DRIt cannot.

What you're seeing is invalid access of memory which invokesundefined 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 toinv(by callingmalloc(1)) isway lessthen it should be. Thus, basically, you're trying to access memory that does not belong to you (your process) and hence that memory isinvalid. Any attempt to access invalid memory results in UB.

Following the same trail, even after you have allocated proper memory forinv, then also

strcpy(inv[0].name,"hello charlie old mate");

will be UB, as you're trying to copy more than20elements into the destination having only size of 20 (which can hold 19 validchars+ 1 null terminator, if you wantnameto be used as astring). Count your memory requirement properly and stay within bounds.

That said, always check for the return value ofmalloc()for success before using the returned pointer.

There is undefined behaviour in your code -

inv = malloc(sizeof(1));      // you allocate size of int
inv[0].ID = 10;
strcpy(inv[0].name,"hello charlie old mate");    //copying more than your buffer can hold

You allocate size equal to that ofintand is not enough for structure and access unauthorized memory.And then thestrcpy, you try to store more contents than the space available.namecan contain19characters and'\0'at end. And the string you copy is larger then19characters.

What Others Are Reading