summaryrefslogtreecommitdiff
path: root/test/malloc/malloc.c
blob: b35e329c0884a04b0d7e27f2cf2cbe328e8e27f0 (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

#include <unistd.h>
#include <stdlib.h>
#include <string.h>
#include <stdio.h>

#define N_PTRS 1000
#define N_ALLOCS 10000
#define MAX_SIZE 0x10000

#define random_size()	(random()%MAX_SIZE)
#define random_ptr()	(random()%N_PTRS)

int test1(void);
int test2(void);

int main(int argc, char *argv[])
{
	return test1() + test2();
}

int test1(void)
{
	void **ptrs;
	int i,j;
	int size;
	int ret = 0;

	srandom(0x19730929);

	ptrs = malloc(N_PTRS*sizeof(void *));

	for(i=0; i<N_PTRS; i++){
		if ((ptrs[i] = malloc(random_size())) == NULL) {
			printf("malloc random failed! %i\n", i);
			++ret;
		}
	}
	for(i=0; i<N_ALLOCS; i++){
		j = random_ptr();
		free(ptrs[j]);

		size = random_size();
		ptrs[j] = malloc(size);
		if (!ptrs[j]) {
			printf("malloc failed! %d\n", i);
			++ret;
		}
		memset(ptrs[j],0,size);
	}
	for(i=0; i<N_PTRS; i++){
		free(ptrs[i]);
	}

	return ret;
}

int test2(void)
{
	void *ptr = NULL;
	int ret = 0;

	ptr = realloc(ptr,100);
	if (!ptr) {
		printf("couldn't realloc() a NULL pointer\n");
		++ret;
	} else {
		free(ptr);
	}
	
	ptr = malloc(100);
	ptr = realloc(ptr, 0);
#ifdef __MALLOC_GLIBC_COMPAT__
	if (!ptr) {
#else
	if (ptr) {
#endif
		printf("realloc(,0) failed\n");
		++ret;
		free(ptr);
	}

	return ret;
}