gcc (GCC) 4.6.3
c89
apache runtime portable libraries
Hello,
Just a simple question I guess I am trying to create a uuid value.
I want me function that creates it to be stand alone (black box) so I can just pass a buffer and the function will do the rest.
Which means I have to declare memory on the heap in that function, as the calling function doesn’t know much to declare. I know this a bad idea, as the callie will have to free the memory after it has finished with it.
Is there any way I can do this better?
When I run this the branch_id_buf is always null after the function returns. However, I have passed it to the function so should not be null when the function returns as it should point to some allocated memory.
Many thanks for any advice,
static void g_get_branch_id(char *branch_id_buf);
int main(void)
{
char *branch_id_buf = NULL;
g_get_branch_id(branch_id_buf);
printf("branch id [ %s ]\n", branch_id_buf);
free(branch_id_buf);
return 0;
}
static void g_get_branch_id(char *branch_id_buf)
{
apr_uuid_t uuid;
#define MAGIC_COOKIE_LENGTH 9
const char *MAGIC_COOKIE = "z9hG4bk-";
const int BRANCH_ID_LENGTH = APR_UUID_FORMATTED_LENGTH + MAGIC_COOKIE_LENGTH;
branch_id_buf = malloc(BRANCH_ID_LENGTH);
if(branch_id_buf == NULL) {
return;
}
strncpy(branch_id_buf, MAGIC_COOKIE, BRANCH_ID_LENGTH);
printf("branch id [ %s ]\n", branch_id_buf);
apr_uuid_get(&uuid);
#define PREFIX_BRANCH_LENGTH 8
apr_uuid_format(branch_id_buf + PREFIX_BRANCH_LENGTH, &uuid);
printf("branch id [ %s ]\n", branch_id_buf);
}
Generally, it is a very bad idea to allocate in one module and free in another. This is exactly how you create numerous memory leaks in your programs. Your code is particularly problematic, as you don’t only leave freeing to the caller, but also the responsibility to initialize the pointer to NULL
That being said, it seems that you are only dealing with compile-time constants (?), so I don’t understand why you even need malloc. Can’t you do like this?
The array length in the prototype indicates to the caller that they should pass a pointer to a buffer with that length.