CS3413/Assignment1/node.c

45 lines
1.5 KiB
C

#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include "node.h"
//Assume that the string passed in is null terminated
Node *createNode(char *data) {
// Allocate memory for the node, and check if it was successful
Node *node = calloc(1, sizeof(Node));
if (node == NULL) {
printf("Error allocating memory for node\n");
exit(EXIT_FAILURE);
}
// Allocate memory for the data, and check if it was successful
node->data = calloc(strlen(data) + 1, sizeof(char));
if (node->data == NULL) {
printf("Error allocating memory for node data\n");
exit(EXIT_FAILURE);
}
// Copy data from the string passed in to the node's data
// Makes sure if the string passed in is changed, the node's data is not changed
// Also makes sure that if the data is on the stack, it is not freed at some other point
strcpy(node->data, data);
node->next_elem = NULL;
return node;
}
void destroyNode(Node *node) {
// Free the data first, then free the node
free(node->data);
free(node);
}
void replaceData(Node *node, char *data) {
// Free the data first, then allocate memory for the new data
free(node->data);
node->data = calloc(strlen(data) + 1, sizeof(char));
if (node->data == NULL) {
printf("Error allocating memory for replacing data\n");
exit(EXIT_FAILURE);
}
// Same rational as for createNode
strcpy(node->data, data);
}