int *ptr=malloc(1);
*ptr=100000;
printf("%d",*ptr);
As the parameter we pass to the malloc function is the bytes of memory we want to allocate, but since integer is of 4 bytes the size we pass must be multiple of four to store the integer the values.
Here I have passed 1(not a multiple of four) as an argument and still it works fine i.e., the program produces the correct output.
I think, since ptr is an integer pointer it will always read the next four bytes starting from the address return by malloc . So,there is no problem in storing and dereferencing four bytes.
@arpit728 segmentation fault is generated by O.S. when you access an illegal memory. for the smallest program some memory is allocated (may be 2mb for C) .So, it has enough space to accomodate this 4 byte without getting segmentation fault.
This piece of code works perfectly fine because of the implicit type casting by the compiler.The integer pointer is implicitly converted to make it point to the starting memory location of the character buffer.
Malloc works slightly in a different way than expected.