3

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);
}
Angus
  • 12,133
  • 29
  • 96
  • 151
  • 3
    The memory allocated for local variables when you call a method is freed when you return from the method, and using pointers referring to that memory after returning is undefined behaviour. If you allocate dynamically on the heap and return a pointer to THAT, if you do that right, that is ok. – Patashu May 13 '13 at 23:58
  • Thanks basile and perreal. I understood now why it is not an undefined behaviour – Angus May 14 '13 at 00:01

2 Answers2

5

Your code look ok, beware that sbrk(2) is nearly obsolete (and thread unfriendly), most malloc implementations use mmap(2) instead.

What is undefined behavior is to return the address of a local variable, like

void* topofstack() {
   char c;
   return &c;
}

and recent GCC compilers (e.g. 4.8) will make a warning, at least with -Wall which you always should use. Regarding call stacks see this answer which gives a lot of useful links.

When coding some malloc, do also code the free (and try to avoid making a syscall too often, so re-use the free-d memory in malloc when possible). Look also into the source code of existing malloc free software implementations. The MUSL libc has some quite readable malloc/ ...

Community
  • 1
  • 1
Basile Starynkevitch
  • 223,805
  • 18
  • 296
  • 547
2

The stack allocated, local storage in my_malloc is p (the address stored in p). You cannot return the address of p (&p) and use it later. However, the allocated space, which is pointed by p, will still be allocated. The address is copied before p is destroyed. This is no different than returning an integer value from a function.

perreal
  • 94,503
  • 21
  • 155
  • 181