开发者

Does malloc allocate memory from 0 to positive infinity?

开发者 https://www.devze.com 2022-12-08 18:34 出处:网络
I wrote a test program thinking that the address of p1 will be less than p2, but when I compiled the code, the address of p2 turned out to be lower (p1 is 8 units larger than p2). I also heard rumors

I wrote a test program thinking that the address of p1 will be less than p2, but when I compiled the code, the address of p2 turned out to be lower (p1 is 8 units larger than p2). I also heard rumors that 2 adjacent memory blocks will combine themselves automatically开发者_StackOverflow. Does that play any part in the following code?

void main(){
    char *p1, *p2;
    p1=malloc(4);
    p2=malloc(5);
    p1="yah";
    p2="goog";
    printf(" p1 = %d, and p2 = %d \n", p1, p2);
}


You are not printing the addresses returned from malloc, but the addresses of the string literals (which are statically allocated). If you want to fill the blocks, use strcpy; doing so is not necessary to print the addresses, though.

Also, use %p to print pointers.


malloc can give you a pointer from anywhere in the heap; it's entirely up to the implementation as to how it allocates memory.

The pointer values are limited to your address space range (so, in a 32-bit address space, you won't get a pointer value greater than 2^32 - 1).


malloc(3) obtains memory from the OS, so the OS, and the way your program is linked, are what determine the addresses that malloc(3) can play with. Because malloc recycles memory, you may be reusing an older allocation, or it may simply decide to hand out the higher addresses first.

However, in your program, you overwrite the malloc address references with references to your string literals. These are allocated in static memory in your image; malloc is not involved.


The OS will determine how to meet the malloc demands, as your program has allocations that went beyond just what you explicitly asked for, and there is no guarantee where it will be allocated at, as this is not physical memory but pointers to some virtual memory that will map to physical memory.

Also, two adjacent blocks won't be merged, as it would then be difficult to determine how to free them, which of the two pointers would free be called with?


"p1 will be less than p2" falls in the realm of "undefined". Something like p1 < p2 is defined only if p1 and p2 point to elements within the same array or struct.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号