Skip to content

Instantly share code, notes, and snippets.

@myaut
Created March 6, 2015 19:28
Show Gist options
  • Save myaut/1824face30c4cc9829e2 to your computer and use it in GitHub Desktop.
Save myaut/1824face30c4cc9829e2 to your computer and use it in GitHub Desktop.
Auto-allocated strings
#include <stdlib.h>
#include <string.h>
#ifdef AAS_STRICT
typedef struct { char a; } *aas_t;
#else
typedef char *aas_t;
#endif
#define AAS_DYNAMIC 'D'
#define AAS_STATIC 'S'
#define AAS_STATIC_PREFIX "S"
#define AAS_CONST_STR(str) ((aas_t) ((AAS_STATIC_PREFIX str) + 1))
aas_t aas_allocate(size_t count) {
char* buffer = malloc(count + 2);
if(buffer == NULL)
return NULL;
*buffer = AAS_DYNAMIC;
return (aas_t) buffer + 1;
}
void aas_free(aas_t aas) {
if(aas != NULL) {
char* buffer = ((char*) aas) - 1;
if(*buffer == AAS_DYNAMIC) {
free(buffer);
}
}
}
int main() {
char* s1 = AAS_CONST_STR("test1");
char* s2 = aas_allocate(10);
strcpy(s2, "test2");
aas_free(s1);
aas_free(s2);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment