int main(){ char *char_ptr; char_ptr = (char *)malloc(20); strcpy(char_ptr, "Hello"); printf("char_ptr (%p) --> %s \n", char_ptr, char_ptr); char_ptr = (char *)malloc(10); strcpy(char_ptr, "He"); printf("char_ptr (%p) --> %s \n", char_ptr, char_ptr); } OUTPUT: char_ptr (0x957c008) --> Hello char_ptr (0x957c020) --> He inthe second printing, it doesnt have to print 2 words together? otherwise WHY so?
What is the question? Also, you don't want to be reallocating memory like that without freeing up the memory you allocated before. In fact, you don't even need to allocate memory a second time. Simply re-use that memory.
it is just a example, assume that firstly 6 bytes loaded,, question is why second time chr_ptr points to 0x957c020, i mean firsly it points to 0x957c008 and "HELLO" is 6 bytes, in the second time it doestsn have to point (0x957c008 +6)?
The second time, you are pointing to a different location in memory.
Oh. Because you allocated 20 characters. So, the first malloc would have allocated that memory for that amount. Then, the second malloc would allocate 10 bytes from a different address. Even though you did not use all the 20 bytes you allocated in the first instance, you still had it reserved. The second malloc won't be able to allocate from this reserved space. I suggest you look up man pages for "malloc" and "free".
first char_ptr has 20 bytes and it points 0x957c008 . it means char_ptr points between 0x957c008 - 0x957c028 (0x957c008+20). and second times char_ptr has 10 bytes and points to 0x957c020 , my question is 0x957c020 is not the location of first char_ptr?
Well, two problems with your math. 1) You are assuming base 10 math. You should do hexadecimal math to calculate address locations. So, in this case, the first allocation would have taken up memory from 0x957c008 to 0x957c01c. Not as you say 0x957028. 2) When you called second malloc using the same pointer variable char_ptr, you essentially abandoned (completely) the first 20 bytes allocated and reallocated a new block of 10 bytes of memory. This second malloc call will reserve those 10 bytes of memory from whatever next "free" block of memory. In your case, it ended up reserving from 0x957c020. The system does not know whether or not you "used" the first 20 bytes fully or not. Just that you asked for that amount and got it. When you ask for more memory, it will allocate new chunks of memory.
I got it, thanks a lot
Join our real-time social learning platform and learn together with your friends!