summaryrefslogtreecommitdiff
path: root/tests/libc/test_malloc.c
blob: e523de90de56dfbe2f5b37c6a04121dc208664f4 (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
#include "stdlib.h"
#include "string.h"

#define HEAP_SIZE 128 * 1024

int main( void )
{
	memory_manager_t memory_manager;
	char buf[HEAP_SIZE];
	uint32_t heap_offset = (uint32_t)&buf;
	size_t heap_size = HEAP_SIZE;
	memory_manager_init( &memory_manager, heap_offset, heap_size );
	__stdlib_set_memory_manager( &memory_manager );
	
	char *s;
	char *s1 = "test_string";

	// simple test if malloced string can be used	
	s = (char *)malloc( strlen( s1 ) + 1 );
	size_t n = strlcpy( s, s1, strlen( s1 ) + 1 );
	if( n != 11 ) exit( 1 );
	if( strcmp( s, s1 ) != 0 ) exit( 1 );
	free( s );

	// test if we are freing all memory and are not leaking

	size_t memory_used_before = memory_manager_stats_used( &memory_manager );

	char *v[120];
	for( int i = 0; i < 120; i++ ) {
		v[i] = (char *)malloc( i );
		if( v[i] == NULL ) exit( 1 );
	}

	for( int i = 119; i >= 0; i-- ) {
		free( v[i] );
	}

	size_t memory_used_after = memory_manager_stats_used( &memory_manager );

	if( memory_used_before != memory_used_after ) exit( 1 );

	exit( 0 );
}