PetaVision  Alpha
PVAlloc.cpp
1 #include "PVAlloc.hpp"
2 #include "utils/PVLog.hpp"
3 #include <stdarg.h>
4 #include <stdio.h>
5 
6 namespace PV {
7 
8 void *pv_malloc(const char *file, int line, size_t size) {
9  void *ptr = malloc(size);
10  FatalIf(ptr == nullptr, file, line, "malloc(%zu) failed\n", size);
11  return ptr;
12 }
13 
14 void *pv_calloc(const char *file, int line, size_t count, size_t size) {
15  void *ptr = calloc(count, size);
16  FatalIf(ptr == nullptr, file, line, "calloc(%zu, %zu) failed\n", count, size);
17  return ptr;
18 }
19 
20 void *pv_malloc(const char *file, int line, size_t size, const char *fmt, ...) {
21  void *ptr = malloc(size);
22  if (ptr == NULL) {
23  /* Build up custom error string */
24  va_list args;
25  va_start(args, fmt);
26  static int buf_size = 1024;
27  char msg[buf_size];
28  vsnprintf(msg, buf_size, fmt, args);
29  va_end(args);
30 
31  /* Log the error */
32  Fatal().printf(file, line, "malloc(%zu) failed: %s\n", size, msg);
33  }
34  return ptr;
35 }
36 
37 void *pv_calloc(const char *file, int line, size_t count, size_t size, const char *fmt, ...) {
38  void *ptr = calloc(count, size);
39  if (ptr == NULL) {
40  /* Build up custom error string */
41  va_list args;
42  va_start(args, fmt);
43  static int buf_size = 1024;
44  char msg[buf_size];
45  vsnprintf(msg, buf_size, fmt, args);
46  va_end(args);
47 
48  /* Log the error */
49  Fatal().printf(file, line, "calloc(%zu, %zu) failed: %s\n", count, size, msg);
50  }
51  return ptr;
52 }
53 }