RicardasSim icon

cleanup();

RicardasSim | PRO | 08/10/20 01:56:29 PM UTC (Edited) | 0 ⭐ | 1584 👁️ | Never ⏰ | []
C |

2.74 KB

|

None

|

0 👍

/

0 👎

//-std=c99 -Wall -Wextra -Wpedantic -Wshadow
 
#include <stdio.h>
#include <stdlib.h>
#include <stdint.h>
#include <stdbool.h>
 
#define TEST_A_MAX_SIZE 1000000 
 
typedef struct test_a
{
    uint32_t *variables;
    uint32_t test_count;
} s_test_a;
 
/*
C99 6.7.8
10.
If an object that has automatic storage duration is not initialized explicitly, its value is indeterminate.
If an object that has static storage duration is not initialized explicitly, then:
-- if it has pointer type, it is initialized to a null pointer;
-- if it has arithmetic type, it is initialized to (positive or unsigned) zero;
-- if it is an aggregate, every member is initialized (recursively) according to these rules;
-- if it is a union, the first named member is initialized (recursively) according to these rules.
*/
 
s_test_a s_1;
s_test_a *s_2;
 
void cleanup()
{
    if ( s_1.variables != NULL )
    {
        free (s_1.variables);
    }
 
    if( s_2 != NULL )
    {
        if ( s_2->variables != NULL )
        {
            free ( s_2->variables );
        }
 
        free ( s_2 );
    }
 
}
 
int main()
{
 
    printf("(1) %p\n", (void*) &s_1);
    printf("(2) %p\n", (void*) s_1.variables);
    printf("(3) %p\n", (void*) s_2);
 
    s_1.variables = malloc( TEST_A_MAX_SIZE * sizeof (uint32_t) );
 
    if ( !s_1.variables )
    {
        printf("Error: cannot allocate memory (1).\n");
        cleanup();
        return 1;
    }
 
    s_2 = malloc( sizeof *s_2 );
 
    if ( !s_2 )
    {
        printf("Error: cannot allocate memory (2).\n");
        cleanup();
        return 1;
    }
 
    s_2->variables = malloc( TEST_A_MAX_SIZE * sizeof (uint32_t) );
 
    if ( !s_2->variables )
    {
        printf("Error: cannot allocate memory (3).\n");
        cleanup();
        return 1;
    }
 
    printf("(4) %p\n", (void*) &s_1);
    printf("(5) %p\n", (void*) s_1.variables);
    printf("(6) %p\n", (void*) s_2);
 
    s_1.test_count = TEST_A_MAX_SIZE;
    s_2->test_count = 10;
 
 
    printf( "%d\n", s_1.test_count );
    printf( "%d\n", s_2->test_count );
 
    s_1.variables[TEST_A_MAX_SIZE-1] = 1;
    s_2->variables[10] = 2;
 
    printf( "%d\n", s_1.variables[TEST_A_MAX_SIZE-1] );
    printf( "%d\n", s_2->variables[10] );
 
    cleanup();
 
    return 0;
}
 
/*
output:
 
(1) 0x559a0e727020
(2) (nil)
(3) (nil)
(4) 0x559a0e727020
(5) 0x7f8d767df010
(6) 0x559a0f0196b0
1000000
10
1
2
 
valgrind:
 
HEAP SUMMARY:
in use at exit: 0 bytes in 0 blocks
total heap usage: 4 allocs, 4 frees, 8,001,040 bytes allocated
 
All heap blocks were freed -- no leaks are possible
 
For lists of detected and suppressed errors, rerun with: -s
ERROR SUMMARY: 0 errors from 0 contexts (suppressed: 0 from 0)
 
*/
 
 

Comments