Detecting Initialized Members In C

closed account (zb0S216C)
Yet again, I'm back with another head-scratcher in C. This is not exactly an error question but a logical solution if you will.

How can I tell if a member( dynamically created ) of a struct has been initialized?

Here's a sample code of what I'm trying to say:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
// Note: This is C, not C++. 
struct Base
{
    int *Member; // Cannot initialize this because constructors don't exist. 
};

// Here's a method that initializes the given Base instance.
bool InitializeBase( struct Base *ThisBase )
{
    if( ThisBase == NULL )
    {
        return false;
    }

    // Initialize Member. This is potential memory leak.
    if( ( ThisBase -> Member = ( ( int * )malloc( sizeof( int ) ) ) == NULL )
    {
        return false;
    }

    return true;
}


How would I know if Member of Base is already allocating memory or pointing to another object? Should I initialize Member after each instance of Base is made?
You can't.

I would probably go with something like the factory pattern (have a function that returns objects) to prevent users from making object but not initializing it. Destructing it is still up them (in C anyway).
Use a factory to create initialized Base objects.

Doh! firedraco beat me to it.
Last edited on
closed account (zb0S216C)
Call me stupid but I've never heard of a Factory Pattern. Can you give me a quick example? If it's not too much trouble.
Here the wiki on it: http://en.wikipedia.org/wiki/Factory_method_pattern

Example:
1
2
3
4
5
6
7
8
Some_struct Create_Some_struct(/*for example*/int a, int b) {
    Some_struct temp;
    //initialize class
    //e.g.
    temp.a = new int(a);
    temp.b = b;
    return temp;
}
closed account (zb0S216C)
I've got an idea how it works now. Thanks, Firedraco.
Topic archived. No new replies allowed.