John Friendson
John Friendson

Reputation: 87

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

Upvotes: 0

Views: 58

Answers (1)

0___________
0___________

Reputation: 68013

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.

enter image description here

Upvotes: 2

Related Questions