简体   繁体   中英

How can I allocate a pointer to a struct in C?

#include <stdlib.h>

struct foo{
        int a;
};

int main(int argc, char * * argv){
        struct foo * bar = malloc(sizeof(struct foo));
        free(bar);
        return EXIT_SUCCESS;
}

Wouldn't this cause undefined behavior according to the standard? If so, what should I do instead to adhere to the standard?

https://stackoverflow.com/a/1241314/13959281

If the question is what will happen if the malloc fails and bar will be assigned NULL , then the answer is: nothing will happen when free is called. free function checks if the pointer passed is NULL . If the pointer is NULL no action is taken. So there is no UB here.

As a general remark: it is safer (or at least less error-prone) if instead of types the actual objects are used:

struct foo * bar = malloc(sizeof(*bar));

#EDIT#

OPs comment clarifies the question. The size of pointer in the implementation does not matter as C standard guarantees that any pointer to object type (not function pointer) can be converted to void * and void * can be converted to any type of pointer. How it is actually done is left to the implementation. So it is 100% safe as it is guaranteed by the C standard.

在此处输入图像描述

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