简体   繁体   中英

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 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?

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 of int and is not enough for structure and access unauthorized memory.And then the strcpy , you try to store more contents than the space available. name can contain 19 characters and '\\0' at end. And the string you copy is larger then 19 characters.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM