Problem in using malloc function?

int *ptr=malloc(1);

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.

Can anyone explain what is happening here.

1 Like

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.

but since memory is allocated to one byte only, and we are trying to access 4 then we should get segmentation fault.

@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.

If what you are saying is correct then this could should also not give segmentation fault;

int main() {

int *ptr="arpit";



int *ptr=“arpit”;


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.

Read this : [][1]

Hope this helps.

(Correct me if I went wrong anywhere)

Dude I am not getting how malloc is working in this scenario.