File: alloca.c

package info (click to toggle)
avr-libc 1%3A1.6.2.cvs20080610-2
  • links: PTS
  • area: main
  • in suites: lenny
  • size: 14,848 kB
  • ctags: 55,619
  • sloc: ansic: 92,267; asm: 6,692; sh: 4,131; makefile: 2,481; python: 976; pascal: 426; perl: 116
file content (94 lines) | stat: -rw-r--r-- 1,884 bytes parent folder | download
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
/* $Id: alloca.c,v 1.1 2007/07/01 06:16:40 dmix Exp $ */

#include <alloca.h>
#include <stdarg.h>
#include <stdlib.h>
#include <string.h>

#define elemof(v)	(sizeof(v) / sizeof((v)[0]))

/* A few of alloca() calls in the one function.	*/
void test_few_alloca (void)
{
    unsigned char *p[10];
    int i, n;

    /* Allocate and fill each block with sizes: 1 .. elemof(p)	*/
    for (n = 1; n < (int)elemof(p); n++) {
	p[n-1] = alloca (n);
	memset (p[n-1], n, n);
    }

    /* Check that there is no overlapping.	*/
    for (n = 1; n < (int)elemof(p); n++) {
	for (i = 0; i < n; i++)
	    if (p[n-1][i] != n)
		exit (__LINE__);
    }
}

/* Variable size array and alloca() together.	*/
void test_with_var_array (int n)
{
    unsigned char s[n];
    unsigned char *p;
    int i;

    /* Fill variable size array.	*/
    memset (s, 1, n);

    /* Allocate and fill the second array.	*/
    p = alloca (n);
    memset (p, 2, n);
    
    /* Refill the first array.	*/
    for (i = 0; i < n; i++) s[i] += 1;

    /* Check both.	*/
    if (memcmp (s, p, n))
	exit (__LINE__);
}

/* Increment the each element of buf[].
   The second argument is the number of elements.	*/
void inc_array (unsigned char *buf, ...)
{
    va_list ap;
    int n, i;
    
    va_start (ap, buf);
    n = va_arg (ap, int);
    va_end (ap);
    
    for (i = 0; i < n; i++) buf[i] += 1;
}

/* Check the compatibility with call of function, where arguments are
   allocated in the stack.	*/
void test_with_var_args (int n)
{
    unsigned char *p;
    int i;

    /* Allocate and fill.	*/
    p = alloca (n);
    memset (p, 1, n);

    /* Args are placed in stack.	*/
    inc_array (p, n);

    /* Check the result.	*/
    for (i = 0; i < n; i++) {
	if (p[i] != 2)
	    exit (__LINE__);
    }
}

int main ()
{
    test_few_alloca ();
    test_with_var_array (10);
    test_with_var_args (20);
    
    return 0;
}