Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is returning a local pointer cause undefined behaviour

Tags:

c

unix

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);
}
like image 951
Angus Avatar asked Aug 24 '26 18:08

Angus


2 Answers

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/ ...

like image 88
Basile Starynkevitch Avatar answered Aug 26 '26 07:08

Basile Starynkevitch


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.

like image 31
perreal Avatar answered Aug 26 '26 06:08

perreal



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!