summaryrefslogtreecommitdiff
path: root/blt/src/bltAlloc.c
blob: 69745f5a7bb74a6d0475217282b9bbf49d1fced7 (plain)
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
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
#include "bltInt.h"

#ifndef linux
#ifdef HAVE_MALLOC_H
#include <malloc.h>
#endif /* HAVE_MALLOC_H */
#endif

/*
 * Blt_MallocProcPtr, Blt_FreeProcPtr --
 *
 *	These global variables allow you to override the default
 *	memory allocation/deallocation routines, simply by setting the
 *	pointers to your own C functions.  By default, we try to use
 *	the same memory allocation scheme that Tcl is using: generally
 *	that's Tcl_Alloc and Tcl_Free.
 */
#ifdef WIN32

#ifdef __CYGWIN__
extern char *Tcl_Alloc _ANSI_ARGS_((unsigned int size));
extern void Tcl_Free _ANSI_ARGS_((char * ptr));
#endif /*__CYGWIN__*/

Blt_MallocProc *Blt_MallocProcPtr = Tcl_Alloc;
Blt_FreeProc *Blt_FreeProcPtr = Tcl_Free; 

#else

/* 
 * Try to use the same memory allocator/deallocator that Tcl is
 * using. Before 8.1 it used malloc/free.
 */

#if (TCL_VERSION_NUMBER >= _VERSION(8,1,0)) 
/* 
 * We're pointing to the private TclpAlloc/TclpFree instead of public
 * Tcl_Alloc/Tcl_Free routines because they don't automatically cause
 * a panic when not enough memory is available. There are cases (such 
 * as allocating a very large vector) where it's recoverable.
 */
EXTERN Blt_MallocProc TclpAlloc;
EXTERN Blt_FreeProc TclpFree;

Blt_MallocProc *Blt_MallocProcPtr = TclpAlloc;
Blt_FreeProc *Blt_FreeProcPtr = TclpFree; 

#else

Blt_MallocProc *Blt_MallocProcPtr = malloc;
Blt_FreeProc *Blt_FreeProcPtr = free; 

#endif /* >= 8.1.0 */
#endif /* WIN32 */

void *
Blt_Calloc(nElems, sizeOfElem)
    unsigned int nElems; 
    size_t sizeOfElem;
{
    char *ptr;
    size_t size;

    size = nElems * sizeOfElem;
    ptr = Blt_Malloc(size);
    if (ptr != NULL) {
	memset(ptr, 0, size);
    }
    return ptr;
}

/*
 *----------------------------------------------------------------------
 *
 * Blt_Strdup --
 *
 *      Create a copy of the string from heap storage.
 *
 * Results:
 *      Returns a pointer to the need string copy.
 *
 *----------------------------------------------------------------------
 */
char *
Blt_Strdup(string)
    CONST char *string;
{
    size_t size;
    char *ptr;

    size = strlen(string) + 1;
    ptr = Blt_Malloc(size * sizeof(char));
    if (ptr != NULL) {
	strcpy(ptr, string);
    }
    return ptr;
}