Alternative to heap allocated strings in C (with long lifetimes) -
is possible use "temporary string objects" in c program?
for example, have reasonably large array of char * objects (part of struct), using heap allocated memory. have opportunity reduce program's memory usage, since of these names can determined without using explicit character array (although not of them can).
in c++, i'd create api returns std::string object (by value) , done it. in c, can come no solutions i'm thrilled about. advice?
here's code, requeted:
struct foo { char *name; ... }; extern foo* global_foo_array; /* in .h file */ void setup_foo(void) { int i; global_foo_array = (foo*) malloc ( get_num_foo() * sizeof(foo) ); (i = 0; < get_num_foo_with_complex_name(); ++i) { global_foo_array.name[i] = malloc ( ... ); } (i = get_num_foo_with_complex_name(); < get_num_foo(); ++i) { char buf[100]; sprintf( buf, "foo #%d", ); global_foo_array[i].name = strdup( buf ); } }
get_num_foo() approximately 100-1000x larger get_num_foo_with_complex_name(). program, part, treats 'global_foo_array[].name' read-only.
i see non-negligible memory savings here , wondering what's best way achieve savings, balancing human investment.
if don't need strings, obvious choice create them on demand:
struct foo { char *name; ... }; static foo* global_foo_array; /* not in .h file */ void setup_foo(void) { int i; global_foo_array = (foo*) malloc ( get_num_foo() * sizeof(foo) ); memset(global_foo_array, 0, get_num_foo() * sizeof(foo) ); } foo *get_foo(int i) { if (i < 0 || > get_num_foo()) return 0; if (!global_foo_array[i].name) { if (i < get_num_foo_with_complex_name()) { global_foo_array.name[i] = malloc ( ... ); } else { char buf[32]; sprintf( buf, "foo #%d", ); global_foo_array[i].name = strdup( buf ); } } return &global_foo_array[i]; }
this still wastes space foo
objects don't need. if large, might better have static foo **global_foo_array
(an level of indirection), , allocate on demand too.
Comments
Post a Comment