Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Segmentation fault after defining my own malloc?

Why does this result in a segmentation fault?

#include <stddef.h>
       
void *malloc(size_t s) {           
};                                                                                                    
int main() {  
  printf("lol");           
}

This is how I compile:

gcc -o l lol.c

My guess is that printf() calls malloc().

like image 627
runningupthatroad Avatar asked Nov 23 '25 17:11

runningupthatroad


1 Answers

Per the C language specification, providing your own definitions of standard library functions as functions with external linkage (which is the default for functions) produces undefined behavior. Those names are reserved for such use (C17 7.1.3). You have observed one of many possible manifestations of such behavior.

You have at least four alternatives:

  1. Just use the standard library's implementation.
  2. Define your function with a different name. For example, my_malloc(). You will then need to use that name to call it, though you could disguise that by use of a macro.
  3. Declare your function static (giving it internal linkage). Then it can have the same name as a standard library function, but only functions defined in the same translation unit (roughly: source file) will be able to call it via that name.
  4. Engage implementation-specific provisions of your particular C implementation (see next).

Some C implementations make implementation-specific provision for programs to provide their own versions of at least some library functions. Glibc is one of these. However, such provisions are subject to significant limits.

  • First and foremost, you can expect that the implementation will require your replacement functions to provide the same binary interface and to correctly implement the behavior specified by the language. (Your function does not do the latter.)

  • Second, where the function is part of a set of related ones, as malloc is, you may find that the implementation requires you to replace the whole set. Indeed, Glibc docs say that "replacing malloc" involves providing replacements for all these functions: malloc, free, calloc, realloc. Your program does not do this, either. The Glibc docs recommend providing replacements for several other functions as well, with the suggestion that failure to do so, while not in itself compromising any Glibc functions, is likely to break some programs: aligned_alloc, cfree,* malloc_usable_size, memalign, posix_memalign, pvalloc, valloc. These latter are not relevant to your particular example, however.


*Required only by very old programs.

like image 67
John Bollinger Avatar answered Nov 26 '25 09:11

John Bollinger



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!