Skip to content

Instantly share code, notes, and snippets.

@splinterofchaos
Last active August 29, 2015 14:04
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save splinterofchaos/449426d26b1f912c8ac6 to your computer and use it in GitHub Desktop.
Save splinterofchaos/449426d26b1f912c8ac6 to your computer and use it in GitHub Desktop.
#include "alloc.h"
void *xcalloc(size_t count, size_t size)
{
void *ret = calloc(count, size);
if (!ret && (!count || !size))
ret = calloc(1, 1);
if (!ret) {
//try_to_free_memory();
ret = calloc(count, size); // warning here
if (!ret && (!count || !size))
ret = calloc(1, 1);
if (!ret) {
printf("Error: Out of memory.\n");
}
}
return ret;
}
void *xmalloc(size_t size)
{
void *ret = malloc(size);
if (!ret && !size)
ret = malloc(1);
if (!ret) {
//try_to_free_memory();
ret = malloc(size); // no warning
if (!ret && !size)
ret = malloc( 1);
if (!ret) {
printf("Error: Out of memory.\n");
}
}
return ret;
}
#include <string.h>
#include <memory.h>
#include <stdlib.h>
#include <stdio.h>
void *xcalloc(size_t, size_t);
void *xmalloc(size_t);
set(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} --coverage")
set(CMAKE_EXE_LINKER_FLAGS "${SMAKE_EXE_LINKER_FLAGS} --coverage")
set(CMAKE_SHARED_LINKER_FLAGS "${CMAKE_SHARED_LINKER_FLAGS} --coverage")
add_library(Alloc alloc.c)
add_executable(Main, main.c)
target_link_libraries(Main, Alloc)
#include "alloc.h"
int main() {
void* p = xcalloc(0,0); // warning expected
void* q = xmalloc(0); // warning expected
printf("int @ %lu = %i\n", (size_t)p, *(int*)p);
printf("int @ %lu = %i\n", (size_t)q, *(int*)q);
free(p);
free(q);
return 0;
}
@splinterofchaos
Copy link
Author

Testes with:

$ cmake -DCMAKE_C_COMPILER=/usr/share/clang/scan-build/ccc-analyzer   
-- Configuring done
-- Generating done
-- Build files have been written to: /home/admin/src/test
$ scan-build make -B 
scan-build: Using '/usr/bin/clang' for static analysis
[ 50%] Building C object CMakeFiles/Alloc.dir/alloc.c.o
/home/admin/src/test/alloc.c:14:11: warning: Call to 'calloc' has an allocation size of 0 bytes
    ret = calloc(count, size);
          ^~~~~~~~~~~~~~~~~~~
1 warning generated.
Linking C static library libAlloc.a
[ 50%] Built target Alloc
[100%] Building C object CMakeFiles/Main,.dir/main.c.o
Linking C executable Main,
[100%] Built target Main,
scan-build: 1 bugs found.
scan-build: Run 'scan-view /tmp/scan-build-2014-07-18-144446-18799-1' to examine bug reports.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment