Nodes will be for simply linked lists, circular lists, maybe later on extending them to work with graphs. I'm trying to be as defensive as possible, will this leak memory? It runs perfectly I'm just concerned about coding style and best practices. Especially regarding the allocation I'm not 100% convinced of my solution. Is it okay to allocate memory for the next component inside the constructor?
// I would have preferred to declare the typedef together with the struct,
// but this doesn't work.
typedef struct node Node;
struct node {
int value;
Node *next;
};
Node *create_node(int value) {
Node *result = malloc(sizeof(Node));
// How necessary are these checks? Under which circumstances
// could this return NULL?
if (result == NULL) {
return NULL;
}
result->next = malloc(sizeof(Node));
if (result->next == NULL) {
free(result);
return NULL;
}
result->value = value;
return result;
}
void destroy_node(Node *node) {
if (node != NULL) {
//This seems necessary. Or is it not? Could I delete the parent
// node and keep the children alive?
destroy_node(node->next);
free(node);
}
}
int main() {
Node *first = create_node(42);
printf("%d\n", first->value);
Node *second = create_node(45);
first->next = second;
printf("%d\n", first->next->value);
destroy_node(first);
return 0;
}