What is purpose of using sizeof
using malloc
in C
?
Why its necessary?
I mean we can use sizeof
but we already know the size(=1000 bytes) what we are allocating in memory?
I am beginner in C so. This might be a very obvious question.
What is purpose of using sizeof
using malloc
in C
?
Why its necessary?
I mean we can use sizeof
but we already know the size(=1000 bytes) what we are allocating in memory?
I am beginner in C so. This might be a very obvious question.
The answer is in the data types. While you know how many objects you want to allocate memory for, you may not want to go through the trouble of mentally computing their size.
Also, what if the composition of these changes later? Then you're screwed and have to edit everything.
So that's irrelevant in your example, without context. But in the case where you want to allocate memory for more complex things (say, a struct with a number of fields), it does become quite important and useful.
char *s = malloc(100 * sizeof(char));
But hey, it's just char
s, it's fine, you could have done that:
char *s = malloc(100);
Generally works. But shooting yourself in the foot, as you'll see below.
int *i = malloc(100 * sizeof(int));
Sure, you could have written that:
int *i = malloc(100 * 4);
That is, assuming you develop for just one architecture you know pretty well.
typedef struct s_listelement{
int dataitem;
struct s_listelement *link;
} t_listelement;
t_listement *le = malloc(sizeof(t_listelement));
Now imagine that linked-list item's structure contains a bunch of other fields...
Would you want to trust sizeof()
, or go have fun and do the math yourself?
Suppose you want to allocate memory for storing int
s. Your initial guess will be, okay I need to have n
integers and each integer requires x
bytes. So space will be n*x
bytes.
But actually this x
depends on architecture. It maybe 16 bit, 32 bit, etc. So to make your code able to work in different environments, it is recommended to use n*sizeof(int)
instead of n*x
.
For example, if you need to allocate space for 10 integers:
int *p=malloc(sizeof(int)*10);
What happens if you change the size of mallocated
?
You will have to 1) calculate again the new size (letting aside multiple target architectures problems, where you will have to calculate the new size in each target), 2) search for all malloc(1000)
, make sure it refers to mallocated
(which might be not obvious) and replace with new size.
You don't have any of these 2 problems using sizeof
. Thus using sizeof
leads to a more maintainable and readable code.