gcc 4.5.1 c89
I have a function that assigns the elements of the following structure:
static struct Config_t {
char protocol[LINE_SIZE];
char mode[LINE_SIZE];
} *app_config = NULL;
The function using malloc and memset to assign and clear the memory.
Once that is done, I have functions that gets the individual elements:
char* get_mode()
{
if(app_config->mode != NULL) {
return app_config->mode;
}
return NULL;
}
Here I am checking that a value has been assigned. And returning NULL if it hasn’t. So in the calling function I can check if a NULL is returned. However, if there a better way to do this?
Many thanks for any suggestions,
In C, returning
NULLfor an error condition is standard practice for functions returning pointers, so you’re in good shape there. (For functions that don’t return pointers, the usual convention is to return0on success and a non-zero error code on error.)Separately, and perhaps a bit off-topic:
modecan’t beNULL, though, can it?app_configcan certainly beNULL, it’s a pointer to a structure, but yourmodeis defined as an array, an intrinsic part of the struct, not as a pointer. You’ll either have the struct, or not, but you won’t have only part of the struct. Simply allocating the memory for the struct will allocate theLINE_SIZEchars formode; in fact,sizeof(struct Config_t) == LINE_SIZE + LINE_SIZE, the structure is an array of characters followed by another array of characters. There are no pointers involved (other thanapp_config, because you’ve defined it as a pointer to the structure).Consequently, to fully allocate your
struct Config_t, just do this:(or
app_config = malloc(sizeof(struct Config_t));if your platform won’t allow the above.) That allocatesmode, nothing else required.If
modewere defined as achar *, that would be different:Now
sizeof(struct Config_t) == 2 * sizeof(void*)(see below), the structure itself consists only of two pointers, not any data that they may point to. Allocating the structure does not allocate any storage for them.(Given your compiler, I felt free to use the
zformat specifier forsize_targuments, as any recent gcc has it [and it’s in the C99 standard, Matthew tells us].)Output (on my 64-bit Linux system):