-
-
Save sgreg/b087854871b130f58b600e2b27ec3721 to your computer and use it in GitHub Desktop.
Dynamic object allocation for fixed sized container ..or something like that
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <stdio.h> | |
#include <stdlib.h> | |
#include "public.h" | |
static struct foo *foo_container[NUM_FOOS]; | |
static int foo_counter; | |
/* | |
* Create new foo object and return it if there's still storage | |
* space available, otherwise do nothing and return NULL. | |
*/ | |
struct foo *create_new_foo(void) | |
{ | |
struct foo *new_foo = NULL; | |
if (foo_counter < NUM_FOOS) { | |
new_foo = malloc(sizeof(struct foo)); | |
foo_container[foo_counter++] = new_foo; | |
} | |
return new_foo; | |
} | |
/* | |
* Return number of allocated foo objects | |
*/ | |
int get_foo_counter(void) | |
{ | |
return foo_counter; | |
} | |
/* | |
* Get foo object at given index, or NULL if there isn't any. | |
*/ | |
struct foo *get_foo(int index) | |
{ | |
if (index < 0 || index >= foo_counter) { | |
return NULL; | |
} | |
return foo_container[index]; | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#ifndef PUBLIC_H | |
#define PUBLIC_H | |
struct foo { | |
int a; | |
int b; | |
}; | |
#define NUM_FOOS 8 | |
struct foo *create_new_foo(void); | |
int get_foo_counter(void); | |
struct foo *get_foo(int index); | |
#endif /* PUBLIC_H */ |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* to compile: gcc -o test private.c test.c */ | |
#include <stdio.h> | |
#include "public.h" | |
int main(void) | |
{ | |
int i; | |
struct foo *foo; | |
/* create foo object for every available space */ | |
for (i = 0; i < NUM_FOOS; i++) { | |
foo = create_new_foo(); | |
printf("created foo #%d at %p, total %d\n", i, foo, get_foo_counter()); | |
} | |
/* create one too many */ | |
foo = create_new_foo(); | |
/* this should fail. */ | |
if (foo == NULL) { | |
puts("exceeded counter, no more objects available"); | |
} else { | |
puts("never mind, this didn't work.."); | |
return 1; | |
} | |
/* print all the objects */ | |
for (i = 0; i < NUM_FOOS + 2; i++) { | |
printf("foo_container[%d] = %p\n", i, get_foo(i)); | |
} | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment