Can I use malloc without sizeof?


Could you please tell me what's the differences between these codes? and give me a clear example?

Thank you
	int* int_ptr = (int*)malloc(5);
	int* sizeOf_int_ptr = (int*)malloc(sizeof(int) * 5);
malloc(5) allocates 5 bytes.

malloc(sizeof(int) * 5) allocates sizeof(int) * 5 bytes. If sizeof(int) is 4 (very common) then it's the same as malloc(20) which allocates 20 bytes (enough to store 5 ints).
Last edited on
Yes, you can use malloc without using sizeof, if you need a specific number of bytes allocated.

Getting memory for a variable type, though, not using sizeof will not work as expected.
There is also calloc(num, size) which allocates memory for num objects with each object being of size bytes. ie it allocates a total of num * size bytes.

In the L2 example this could be:

int* call_int_ptr = (int*)calloc(5, sizeof(int));

which allocates memory for 5 ints irrespective of the size of an int for that platform.
Last edited on
Be aware that the size of basic types like int or long is not fixed in C/C++, but is platform-specific.

A single int may be 4 bytes (32-Bit) in size on most platforms today, but could also be 8 bytes (64-Bit) or maybe only 2 bytes (16-Bit). The malloc() function is rather "dumb" and simply allocates whichever number of bytes that you asked for. Consequently, in order to write portable code, you better use the sizeof() operator to determine the actual size of a the data type that you intend to allocate - instead of making assumptions about its size!

Either that, or, if you are programming in C++, use the new operator:
int *ptr = new int;         // <-- similar to "(int*)malloc(sizeof(int))"
int *array = new int[42];   // <-- similar to "(int*)malloc(42 * sizeof(int))" 

If memory was allocated by new or new[], then you have to use delete or delete[] instead of free() to free it!
Last edited on
Topic archived. No new replies allowed.