int x=(int)malloc(sizeof(float));
or
int y=(int)calloc(1,sizeof(double));
So in short, if I ask for a greater block of memory using malloc()
or calloc()
but assign it to a variable of smaller memory then what happens to the extra memory?
int x=(int)malloc(sizeof(float));
or
int y=(int)calloc(1,sizeof(double));
So in short, if I ask for a greater block of memory using malloc()
or calloc()
but assign it to a variable of smaller memory then what happens to the extra memory?
First of all, malloc()
and family returns a pointer to void
(void *
), which we store into a "pointer-to-type" and later use that pointer to store values of "type" into the memory location.
As for the call to malloc()
and family, we pass the required size in bytes and they return a pointer to the requested memory area (in bytes), if success. So, as long as x
, y
and z
evaluates to same,
int * p = malloc(x);
or,
int * p = malloc(y);
or
int * p = malloc(z);
will return the same amount of memory.
Now, if it happens, on your platform, sizeof(int) == sizeof(float) == 4
, then, we can write
int * p = malloc(sizeof(int));
or,
int * q = malloc(sizeof(float));
or
int * r = malloc(4);
and they all will return the same amount of memory.
Note: The above statements are just for illustration, the best possible way to use
malloc()
is to use the form<someType> * var = malloc(sizeof(*var));
FWIW, (as you did in your code) assigning a pointer to an integer type is implementation-defined behavior. In general, don't do that.
That said, you're always free to allocate more memory than you need, there's no problem from the C perspective, as long as you free()
that. For example, you can allocate space for 10 integers while you end up using only 5 of them. There's no technical problem in that.
if we have following line of code
int *x=(int*)malloc(sizeof(float));
Here malloc returns a pointer which is then typecasted to integer type of pointer.
Assuming that float has size of 4 bytes and int of 2 bytes. Now argument that is passed to malloc
is only number of bytes you want to allocate. Here sizeof(float)
returns 4 and 4 bytes are allocated and malloc returns a pointer to first bytes that is allocated. So in this case there are two integer spaces allocated and this is continuous allocation. So first two bytes for first int and next 2 bytes is next integer and it becomes an array.
We can access them as
x[0] which is same as *(x+0) and x[1] which is same as *(x+1).
In short rest of two bytes will be the next integer and there is no problem with that.