Re: Use of sizeof in Malloc
You need to have sizeof which is the base for achieving the functionality of malloc. In other words malloc allocates size bytes of memory mentioned. If the allocation succeeds, a pointer to the block of memory is returned. Yes it would return compilation error if a C program is coded without malloc
Re: Use of sizeof in Malloc
[B][U]No it is not essential to use sizeof() operator in malloc().[/U][/B]
The prototype of malloc() function is :
type pointer= (type *) malloc(number of bytes);
Thus you can see that we only need to specify the no of bytes that should be allocated. For example
[B]int *p ;
p=(int *)malloc(10);[/B]
This would allocate 10 bytes of memory and return the starting address of the allocated space.
You generally use sizeof() in malloc() while working with data structures (i.e tree, linked list) to specify the no of bytes to be allocated for each node.
Re: Use of sizeof in Malloc
The sizeof() operator is not essential in malloc,but it is used so that your program can run on all type of machine architecture.
*****************************
int *p ;
p=(int *)malloc(10);
This code is ok where int is allocated 2 bytes.
*********************************
again one more disadvantage if you write
int *p;
p=(int *)malloc(9);
There is chances of error bec 9 is not multiple of 2.
******************************
Again on some machine int is allocated 4 bytes in that case the above mention code may
cause some runtime error.
so it is nice to use
int *p;
p=(int *)malloc(5*sizeof(int));
generalized form:
***************************
datatype *p;
p=(datatype *)malloc(no of block u want*sizeof(datatype));
Re: Use of sizeof in Malloc
You don't [i]have[/i] to use the [FONT="Courier New"]sizeof[/FONT] operator in the [font="Courier New"]malloc()[/font] call, especially if you're just allocating arrays of [font="Courier New"]char[/font] ([FONT="Courier New"]sizeof (char) == 1[/FONT] by definition). However, if you're allocating arrays of types other than [FONT="Courier New"]char[/font], it makes life a lot simpler.
The canonical form for using [font="Courier New"]malloc()[/font] is
[code]
#include <stdlib.h>
...
T *p = malloc(sizeof *p * number_of_elements);
[/code]
for any type T (although it's redundant if T is [font="Courier New"]char[/font]).
This way, we only have to worry about the number of [i]elements[/i] in p, not the number of [i]bytes[/i]. We will always allocate the correct number of bytes for those elements based on the type of p.
Compare this to something like
[code]
int *p = malloc(11);
[/code]
Unless [font="Courier New"]sizeof (int) == 1[/font], this will create a problem, since we haven't allocated enough bytes for the last element in the array.