Skip to content

Instantly share code, notes, and snippets.

@sgreg

sgreg/private.c Secret

Created August 6, 2017 10:05
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save sgreg/b087854871b130f58b600e2b27ec3721 to your computer and use it in GitHub Desktop.
Save sgreg/b087854871b130f58b600e2b27ec3721 to your computer and use it in GitHub Desktop.
Dynamic object allocation for fixed sized container ..or something like that
#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];
}
#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 */
/* 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