I have a doubt in the statement
p = my_malloc(4);
my_malloc has a local pointer called p, when the function returns the address of the pointer will be deallocated. So how is it int* p in main could hold the address returned by the function. When a function returns, the address it used may or may not be used by other functions or processes. So is this below program an undefined behaviour?
#include<stdio.h>
#include<unistd.h>
void* my_malloc(size_t size){
void *p;
p = sbrk(0);
p = sbrk(size); // This will give the previous address
//p = sbrk(0); // This will give the current address
if(p != (void *)-1){
printf("\n address of p : 0x%x \n",(unsigned int)p);
}
else{
printf("\n Unable to allocate memory! \n");
return NULL;
}
return p;
}
int main(){
int* p;
p = my_malloc(4);
printf("\n address of p : 0x%x \n",(unsigned int)p);
}