K
Khookie
Hi everyone
I'm not sure whether this is good practice or not, so I thought I'll
ask.
I've got a function that returns a char pointer, which is malloc'ed in
the function itself, as per below code. It's basically a singly
linked list of strings that are concatenated into a big string.
My question is - since you have to know to free it yourself (usage
below), is this considered bad practice? Or should the user of the
function know?
Function:
char* string_list_concat(string_list *list) {
char* result = malloc(list->length + 1);
char* result_ptr = result;
// Create string
string_node *node = list->bol;
while (node != list->eol) {
char* string_node_ptr = node->string;
while(*string_node_ptr != '\0') {
*result_ptr = *string_node_ptr;
string_node_ptr++;
result_ptr++;
}
node = node->next;
}
*result_ptr = '\0';
return result;
}
Usage:
char* result = string_list_concat(list);
printf("Output is: %s\n", result);
free(result);
Cheers
Chris
I'm not sure whether this is good practice or not, so I thought I'll
ask.
I've got a function that returns a char pointer, which is malloc'ed in
the function itself, as per below code. It's basically a singly
linked list of strings that are concatenated into a big string.
My question is - since you have to know to free it yourself (usage
below), is this considered bad practice? Or should the user of the
function know?
Function:
char* string_list_concat(string_list *list) {
char* result = malloc(list->length + 1);
char* result_ptr = result;
// Create string
string_node *node = list->bol;
while (node != list->eol) {
char* string_node_ptr = node->string;
while(*string_node_ptr != '\0') {
*result_ptr = *string_node_ptr;
string_node_ptr++;
result_ptr++;
}
node = node->next;
}
*result_ptr = '\0';
return result;
}
Usage:
char* result = string_list_concat(list);
printf("Output is: %s\n", result);
free(result);
Cheers
Chris