From 3b8b217f7c75bc19d01f31c43d651c2441a3b5be Mon Sep 17 00:00:00 2001 From: Sumit Bose Date: Mon, 24 Jan 2011 12:09:36 +0100 Subject: [PATCH 5/5] Check if malloc() failed The should fix Coverity issue 10074. --- dhash/examples/dhash_example.c | 18 ++++++++++++++++-- 1 files changed, 16 insertions(+), 2 deletions(-) diff --git a/dhash/examples/dhash_example.c b/dhash/examples/dhash_example.c index c7eac3d..06a3d2d 100644 --- a/dhash/examples/dhash_example.c +++ b/dhash/examples/dhash_example.c @@ -22,6 +22,7 @@ #include #include #include +#include #include "dhash.h" struct my_data_t { @@ -47,7 +48,14 @@ bool visit_callback(hash_entry_t *entry, void *user_data) struct my_data_t *new_data(int foo, const char *bar) { - struct my_data_t *my_data = malloc(sizeof(struct my_data_t)); + struct my_data_t *my_data; + + my_data = malloc(sizeof(struct my_data_t)); + if (my_data == NULL) { + fprintf(stderr, "malloc() failed.\n"); + return NULL; + } + my_data->foo = foo; strncpy(my_data->bar, bar, sizeof(my_data->bar)); return my_data; @@ -61,9 +69,15 @@ int main(int argc, char **argv) hash_entry_t *entry; unsigned long i, n_entries; int error; - struct my_data_t *my_data = new_data(1024, "Hello World!"); + struct my_data_t *my_data; unsigned long count; + my_data = new_data(1024, "Hello World!"); + if (my_data == NULL) { + fprintf(stderr, "new_data() failed.\n"); + return ENOMEM; + } + /* Create a hash table */ error = hash_create(10, &table, delete_callback, NULL); if (error != HASH_SUCCESS) { -- 1.7.3.3