cheater cheater - 8 months ago 31
C Question

different ways to allocate memory for a data structure on c programming language

On C programming language, I have encountered several ways to allocate memory for a data structure:

#include <stdio.h>
#include <stdlib.h>

typedef struct Element
int number;
struct Element *next;

int main(int argc, char *argv[])
/* Method NO.1 */
Element *ptr1 = malloc(sizeof(*ptr1));
/* Method NO.2 */
Element *ptr2 = malloc(sizeof(Element));
/* Method NO.3 */
Element *ptr3 = (Element*) malloc (sizeof(Element));


There are no compilation errors.

But I got confused, so what is the difference beteween them, and which one should be preferred?

  1. The best way by, in my opinion, a country mile. Remember that sizeof *ptr1 is compile-time evaluable so there's no chance of a run-time crash due to dereferencing an uninitialised pointer.

  2. Not my favourite way - despite it arguably being the most readable - since you might change the type of *ptr2 and forget to adjust sizeof Element. And those kind of bugs are a nightmare to track down.

  3. Is horrible: the cast is unnecessary in C and is even occasionally harmful. See Do I cast the result of malloc?.