Search code examples
cmalloccalloc

Memory allocation (calloc, malloc) for unsigned int


For my C application I tried to initialize memory. I am aware of the slower calloc, but fortunatelly there is no need to track performance.

I need memory space for just one unsigned int element (up to 65535).

This is the part of my code that doesn't work:

//Declaration
unsigned int part1;

//Allocation
part1 = (unsigned int) calloc (1,sizeof(unsigned int));

That throws the compiler warning:

warning: cast from pointer to integer of different size [-Wpointer-to-int-cast]

Why does the above code doesn't work, where...

unsigned long size;
size =(unsigned long) calloc (1,sizeof(unsigned long));

...works great?

Thank you!


Solution

  • calloc returns void* so you should use it like

    unsigned int* part1 = calloc (1,sizeof(*part1));
    

    then assign it like

    *part1 = 42;
    

    If you have allocated space for several elements

    part1[0] = 42; // valid indices are [0..nmemb-1]
    

    may be clearer.

    Note that you also have to free this memory later

    free(part1);
    

    Alternatively, if you only need a single element, just declare it on the stack

    unsigned int part1 = 42;
    

    Regarding why casting a point to unsigned long doesn't generate a warning, sizeof(void*)==sizeof(unsigned long) on your platform. Your code would not be portable if you relied on this. More importantly, if you use a pointer to store a single integer, you'd leak your newly allocated memory and be unable to ever store more than one element of an array.