Reputation: 11
I can't understand the reason of the output pf the following program
#include <stdio.h>
#include <stdlib.h>
int main(){
int* ip = (int*)malloc(100*sizeof(int));
if (ip){
int i;
for (i=0; i < 100; i++)
ip[i] = i*i;
}
free(ip);
int* ip2 = (int*)malloc(10*sizeof(int));
printf("%d\n", ip[5]);
printf("%d\n", ip2[5]);
ip[5] = 10;
printf("%d\n", ip2[5]);
return 0;
}
the output shows that ip & ip2 will have the same reference in the heap. when we allocate a 100 int in(ip2) how did it return the same reference for ip1. is it a feature of malloc function? I know that malloc work like "new",right? if it does then it should return some random reference,right?
Upvotes: 0
Views: 109
Reputation: 12658
This is a undefined behaviour which you shouldn't rely on. When you allocate a memory typically from a page memory, when you free it isn't freed to OS immediately and when try allocating again most likely you get the same which is hot in the cache. Typical OS memory unit allocates the same size in next iteration from same memory freed blocks in LIFO fashion.
Upvotes: 0
Reputation: 91017
I don't really see what your problem is.
It is completely up to the library where it allocates the memory which is returned to you. Especially, it may or may not use the most recently freed memory block, as long as it is still free.
Your first malloc()
reserves some memory, you write to it and then you free it.
Your second malloc()
reserves some memory, you read from it then you free it.
What you read in the second step is completely arbitrary and only by coincidence the same as wou wrote to it in the first step.
You code also shows undefined behaviour, because you are not allowed to access ip[5]
after the free(it)
.
Upvotes: 0
Reputation: 16876
All your outputs are undefined behavior, so they're not indicative of anything:
printf("%d\n", ip[5]); // ip was freed, so the memory it points to may not be accessed
printf("%d\n", ip2[5]); // reading uninitialized memory
ip[5] = 10; // writing to freed memory
printf("%d\n", ip2[5]); // still reading uninitialized memory
Generally, it's entirely possible that ip2
gets the same address that ip
had. But you're not testing that in your code. You could do that like this, for instance:
#include <stdio.h>
#include <stdlib.h>
int main() {
int* ip = (int*)malloc(100 * sizeof(int));
printf("%p\n", ip);
free(ip);
int* ip2 = (int*)malloc(100 * sizeof(int));
printf("%p\n", ip2);
free(ip2);
}
When I run that, I do actually get the same address twice (but there's no guarantee that this happens).
Upvotes: 6