- malloc (100); will it return 100 bytes ?
malloc(100)
will return either a pointer to where 100 bytes of memory has been reserved or a null pointer.
- Here i'm not typecasting return addr of malloc,…
The simple assignment operator (=
) automatically converts its right operand to the type of the left operand. When the left operand is a pointer, the right operand may be either of:
- a pointer to a compatible type or to
void
except that the right type may omit qualifiers that the left type has or
- a null pointer constant.
BTW malloc will return void type correct how ptr+1 increments 4 byte ?
C does not “remember” that an address came from malloc
with return type void *
. When ptr+1
is evaluated, the type of ptr
is used for the arithmetic. The type of ptr
is int *
, so the arithmetic is performed in units of int
.
- Now incrementing ptr+100, so 400 byte will get incremented correct ?
Within the allocated space, adding x will add 4x bytes to the address, if the C implementation uses four bytes for int
. Outside of the allocated space, the C standard does not define the behavior of pointer arithmetic. If the allocated space were 1000 bytes instead of 100, then ptr+100
would calculate the address 400 bytes beyond the start.
… also i can able to assign value with out segmentation fault how it works ?
Memory protect usually works in units of pages. If you use memory that is within a page you have access to, there is no segmentation fault even if it is not a place in the page you should be accessing the way you access it. Or, if you calculate an address incorrectly and the result is still a page you have access to, there is no segmentation fault. Memory protection does not absolutely prevent all address mistakes by a process, and dynamically allocated memory is likely to be in a region with many pages that the program is permitted to access.