forked from lxm1117/pDE_codes
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathxmalloc.c
68 lines (56 loc) · 2.04 KB
/
xmalloc.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
/* ========================================================================
pDE: Parallel version of Storn and Price's Differential evolution
applied to NEURON modeling
c2005 Jose Ambros-Ingerson jose@kiubo.net
$Date: 2005/05/20 19:49:14 $ $Log: xmalloc.c,v $
$Date$ Revision 1.1.1.1 2005/05/20 19:49:14 jose
$Date$ Parallel Differential Evolution
$Date$
======================================================================== */
#include <stdio.h>
#include <stdlib.h>
/* #include <malloc.h> This is part of stdlib.h in mac OSX */
#include "jLib.h"
#define MAGIC (double)1234567890.1234456789
/* ================================================================================== */
static void xmfatal( str )
char *str;
{
(void) fprintf( stderr,"%s\n", str );
exit( 1 );
}
/* ===================================================================================
A safer saner malloc, for careless programmers
=================================================================================== */
char *xmalloc( int n )
{
register char *ptr;
if( (ptr = malloc((unsigned)(n + sizeof(double)) )) == NULL)
xmfatal("xmalloc: no memory");
*((double *) ptr) = MAGIC; /* magic number */
return(ptr + sizeof(double));
}
/* ================================================================================ */
/* we make sure realloc will do a malloc if needed */
char *xrealloc( char *ptr, int n )
{
if (ptr == NULL)
return(xmalloc(n));
ptr -= sizeof(double);
if (*((double *) ptr) != MAGIC)
xmfatal("xrealloc: storage not xmalloc'ed");
if ((ptr = realloc(ptr, (unsigned)(n + sizeof(double)) )) == NULL)
xmfatal("xmalloc: no memory");
*((double *) ptr) = MAGIC; /* magic number */
return(ptr + sizeof(double));
}
/* ================================================================================== */
void xfree( char *p )
{
if (p == NULL)
xmfatal("xfree: NULL pointer");
p -= sizeof(double);
if (*((double *) p) != MAGIC)
xmfatal("xfree: storage not xmalloc'ed");
free(p);
}