Question

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!

Was it helpful?

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.

OTHER TIPS

Use code below. Calloc() will return void* So you will have to convert it in the SomeType*

unsigned int* part1;

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

you have to understand these types of memory allocation to avoid doing these errors :

Static memory allocation:

unsigned int part1;

The size is fixed. It needs to be known at compile time. Freeing the memory is done on scope exit directly. The variable is allocated on the stack. indeed, this type of memory allocation is done at compile time, its lifetime is entire runtime of program. the advantage of using this type of allocation is efficient execution time. but if we declare more static data space than we need we waste space, this is the disadvantage of this type.

Dynamic memory allocation:

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

The size can vary, you can find the value at runtime. You are responsible for freeing the memory with free() predefined C function. The variable is allocated on the heap.

you can see more details in web site : http://www.cs.virginia.edu/~son/cs414.f05/lec11.slides.pdf

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top