c - Is returning a local pointer cause undefined behaviour -
i have doubt in statement
p = my_malloc(4);
my_malloc has local pointer called p, when function returns address of pointer deallocated. how int* p in main hold address returned function. when function returns, address used may or may not used other functions or processes. below program undefined behaviour?
#include<stdio.h> #include<unistd.h> void* my_malloc(size_t size){ void *p; p = sbrk(0); p = sbrk(size); // give previous address //p = sbrk(0); // give current address if(p != (void *)-1){ printf("\n address of p : 0x%x \n",(unsigned int)p); } else{ printf("\n unable 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); }
your code ok, beware sbrk(2) obsolete (and thread unfriendly), malloc implementations use mmap(2) instead.
what undefined behavior return address of local variable,
void* topofstack() { char c; return &c; }
and recent gcc compilers (e.g. 4.8) make warning, @ least -wall
should use. regarding call stacks see this answer gives lot of useful links.
when coding malloc
, code free
(and try avoid making syscall often, re-use free
-d memory in malloc
when possible). source code of existing malloc free software implementations. musl libc has quite readable malloc/ ...
Comments
Post a Comment