Allocating memory for a part of structure

后端 未结 2 364
轮回少年
轮回少年 2021-01-12 01:16

I have the following example

#include 
#include 
#include 

typedef struct test{
    int a;
    long b;
    in         


        
2条回答
  •  逝去的感伤
    2021-01-12 01:59

    since the pointer returned by malloc is completely valid.

    No the pointer is not "completely valid". Not at all.

    Why do you think the pointer is "completely valid"? You didn't allocate enough bytes to hold an entire struct test - the pointer is not "completely valid" as there isn't a valid struct test object for you to access.

    There's no such thing as a partial object in C. That's why you can't find it in the C standard.

    It works fine

    No, it doesn't.

    "I didn't observe it blowing up." is not the same as "It works fine."

    Your code doesn't do anything observable. Per the as-if rule the compiler is free to elide the entire thing and just return zero from main().

提交回复
热议问题