#include<stdio.h>
#include<stdlib.h>
int main() {
int *n = malloc(sizeof(int*));//line 1
scanf("%d",n);
printf("%d",*n);
}
I am not sure what is happening here. Does line 1 (in the snippet above) mean n now simply is a pointer to an int? And we have started using the memory allocated for a pointer as variable itself? Is the pointer to pointer cast to pointer to int?
CodePudding user response:
In this line
int *n = malloc(sizeof(int*));//line 1
you allocated memory of the size equal to sizeof( int * )
and its address is assigned to the pointer n
having the type int *
.
So using this pointer to access the memory it is interpreted as a memory storing an object of the type int
scanf("%d",n);
printf("%d",*n);
Actually the kind of the argument expression used to specify the size of the allocated memory is not very important. For example you could just write
int *n = malloc( 8 );//line 1
CodePudding user response:
malloc
knows nothing about types, it only cares about the size.
The correct incantations are
T *t = malloc(sizeof(*t)); // or
T *t = malloc(sizeof(T));
If you pass any other expression to malloc
and it by sheer coincidence happens to have the correct value, you get lucky and nothing bad happens. But this is confusing. Do not confuse the readers of your code.
If the value passed to malloc
is greater than the correct one, you just waste memory. If it is less, you risk Undefined Behaviour.
It is implementation defined whether sizeof(int)
is the same as, larger than, or smaller than sizeof(int*)
so just don't do that.