0
#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

dreamcrash
  • 47,137
  • 25
  • 94
  • 117
  • 2
    *Wouldn't this cause undefined behavior*. In what way do you think it causes UB? Can you please explain in more detail where and why you think there is a problem in this code? And what exactly does the other post referenced have to do with your question? – kaylum Jan 30 '21 at 11:07
  • @kaylum The other post referenced talks about how different pointer types may have different sizes. I was wondering if there was a possibility that the void * that malloc returns would have a different size than struct foo *. If it were, then that should be undefined behavior. – John Friendson Jan 30 '21 at 11:20
  • Thanks for the clarification. Suggest you [Edit](https://stackoverflow.com/posts/65967232/edit) your question with that clarification as it really isn't very clear as currently stated. – kaylum Jan 30 '21 at 11:27
  • @JohnFriendson Hi, could add a text to why you added the link https://stackoverflow.com/a/1241314/13959281 – dreamcrash Jan 30 '21 at 11:28

1 Answers1

2

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

0___________
  • 60,014
  • 4
  • 34
  • 74
  • Thank you, this answers my question. https://pubs.opengroup.org/onlinepubs/009695399/functions/malloc.html It says more regarding this here, that in particular, what malloc returns may be casted to any type. – John Friendson Jan 30 '21 at 11:26