Problem in using malloc function?

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.

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.

int *ptr=“arpit”;

printf(“%s”,ptr);

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 : [c - Why does malloc allocate a different number of bytes than requested? - Stack Overflow][1]

Hope this helps.

(Correct me if I went wrong anywhere)
[1]: c - Why does malloc allocate a different number of bytes than requested? - Stack Overflow

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

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

int main() {

int *ptr="arpit";

printf("%s",ptr);

}

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