The syntax of malloc
is malloc(num*sizeof(data_type))
I wonder why you need to specify a size at all. You could just specify a "large enough" number and everything will run fine.
The syntax of malloc
is malloc(num*sizeof(data_type))
I wonder why you need to specify a size at all. You could just specify a "large enough" number and everything will run fine.
The syntax is malloc(size)
. The only reason you're writing it as, for instance malloc(10*sizeof(int))
is because you're very rarely interested in the exact amount of bytes, but rather the amounts of elements. This also makes it portable and easier to change.
If you know that the size of int
is 4 bytes (can vary from system to system) it is perfectly valid to write malloc(40)
instead of malloc(10*sizeof(int))
but this can cause bugs if you recompile for a different system, or later decides that you need a long
instead of an int
.
And you need to specify a size. When you're invoking malloc(20)
you will get a pointer that points to a chunk of memory that's 20 bytes. If you later realize this is not enough, you can use realloc
to change the size. But you do need to specify a size, cause otherwise the OS will simply not know how much memory to give to you. Also, if malloc
fails, it will give you a NULL
pointer. One reason to fail is that you ask for more memory than currently available.
You CAN ask for more memory than you need. But what's the reason? The consequence will be that your program will demand more memory. That's not a good thing.
Sidenote:
You MAY get more memory than you request. malloc
guarantees that you get at least the amount you ask for, unless the allocation fails. However, you should - for obvious reasons - never count on it.