Project

General

Profile

test_malloc.c

malloc test c file - ddegroot, 12/18/2017 09:25 AM

 
1
#include <stdio.h>
2
#include <stdlib.h>
3
#include <stdint.h>
4
#include <errno.h>
5

    
6
// On Linux
7
#if !defined(SIZE_MAX)
8
#define SIZE_MAX __SIZE_MAX__                // ((size_t)-1) = 9223372036854775807 = LONG_MAX
9
#endif
10
// On DragonFlyBSD
11
//#define SIZE_MAX UINT64_MAX  // from /usr/include/machine/int_limits.h
12

    
13
int main () {
14
  printf("SIZE_MAX=%lu\n", SIZE_MAX);
15
  
16
  unsigned long tests[] = {
17
    9223372036854775807,
18
    223372036854775808,
19
    23372036854775808,
20
    3372036854775808,
21
    372036854775808,
22
    72036854775808,
23
    2036854775808,
24
    36854775808,
25
    INTPTR_MAX,
26
    UINTPTR_MAX,
27
    SIZE_MAX - 2,
28
    SIZE_MAX,
29
    SIZE_MAX + 'a',
30
    SIZE_MAX + SIZE_MAX,
31
    SIZE_MAX * 20};
32
  
33
  for (int test = 0; test < 14; test++) {
34
    printf("test%d: malloc size:%lu, ", test, tests[test]);
35

    
36
    uint *ptr = (int *) malloc(tests[test]);
37
    if (ptr == NULL) {
38
        printf("malloc failed, ptr == NULL, errno:%d\n", errno);
39
    } else {
40
        printf(" ptr == %p\n", ptr);
41
        free(ptr);
42
        ptr = NULL;
43
    }
44
  }
45
  return 0;
46
}