If `malloc(0)` returns a non-null pointer, can I pass that to `free`?

The C99 standard (actually WG14/N1124. Committee Draft — May 6, 2005. ISO/IEC 9899:TC2) says about malloc(): The pointer returned points to the start (lowest byte address) of the allocated space. If the space cannot be allocated, a null pointer is returned. If the size of the space requested is zero, the behavior is implementation defined: … Read more

Is it well-defined to use a pointer pointing to one-past-malloc?

The draft n4296 for C11 is explicit that pointing one past an array is perfecly defined: 6.5.6 Language / Expressions / Additive operators: ยง 8 When an expression that has integer type is added to or subtracted from a pointer, the result has the type of the pointer operand. … Moreover, if the expression P … Read more

Overriding ‘malloc’ using the LD_PRELOAD mechanism

I always do it this way: #define _GNU_SOURCE #include <stdio.h> #include <dlfcn.h> static void* (*real_malloc)(size_t)=NULL; static void mtrace_init(void) { real_malloc = dlsym(RTLD_NEXT, “malloc”); if (NULL == real_malloc) { fprintf(stderr, “Error in `dlsym`: %s\n”, dlerror()); } } void *malloc(size_t size) { if(real_malloc==NULL) { mtrace_init(); } void *p = NULL; fprintf(stderr, “malloc(%d) = “, size); p = … Read more

difference between and

The <malloc.h> header is deprecated (and quite Linux specific, on which it defines non-standard functions like mallinfo(3)). Use <stdlib.h> instead if you simply need malloc(3) and related standard functions (e.g. free, calloc, realloc ….). Notice that <stdlib.h> is defined by C89 (and later) standards, but not <malloc.h> Look into /usr/include/malloc.h you’ll find there some non-standard … Read more

sprintf() with automatic memory allocation?

Here is the original answer from Stack Overflow. As others have mentioned, you need snprintf not sprintf. Make sure the second argument to snprintf is zero. That will prevent snprintf from writing to the NULL string that is the first argument. The second argument is needed because it tells snprintf that enough space is not … Read more

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)