summaryrefslogtreecommitdiff
path: root/src/pal/tests/palsuite/c_runtime/realloc/test1/test1.c
blob: d0dd128cc11f149e646a5c8158ab31566b13dd59 (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
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.

/*============================================================================
**
** Source:  test1.c
**
** Purpose: Uses realloc to allocate and realloate memory, checking
**          that memory contents are copied when the memory is reallocated.
**
**
**==========================================================================*/

#include <palsuite.h>

int __cdecl main(int argc, char **argv)
{
    char *testA;
    const int len1 = 10;
    const char str1[] = "aaaaaaaaaa";

    const int len2 = 20;
    const char str2[] = "bbbbbbbbbbbbbbbbbbbb";

    if (PAL_Initialize(argc, argv))
    {
        return FAIL;
    }

    /* this should work like malloc */
    testA = (char *)realloc(NULL, len1*sizeof(char));  
    memcpy(testA, str1, len1);
    if (testA == NULL)
    {
        Fail("We ran out of memory (unlikely), or realloc is broken.\n");
    }

    if (memcmp(testA, str1, len1) != 0)
    { 
        Fail("realloc doesn't properly allocate new memory.\n");
    }
  
    testA = (char *)realloc(testA, len2*sizeof(char));  
    if (memcmp(testA, str1, len1) != 0)
    { 
        Fail("realloc doesn't move the contents of the original memory "
             "block to the newly allocated block.\n");
    }

    memcpy(testA, str2, len2);
    if (memcmp(testA, str2, len2) != 0)
    {
        Fail("Couldn't write to memory allocated by realloc.\n");
    }

    /* free the buffer */
    testA = realloc(testA, 0);
    if (testA != NULL)
    {
        Fail("Realloc didn't return NULL when called with a length "
             "of zero.\n");
    }
    PAL_Terminate();
    return PASS;
}