I’m writing a function that creates a linked list of string data for results returned from an SQL query made with ODBC. I know that the columns and rows it returns might be of random length so I’m trying to find the best way to go abouts calculating just enough memory to hold that column or row (max row length is 8KB!) and avoid using arrays.
I’ve currently built a function that adds the returned string value from an SQL query, and it is as follows.
// Structure to hold columns and rows
typedef struct node {
SQLCHAR* data;
struct node* next;
} node;
void AppendData(node** root, SQLCHAR* name) {
node* newNode = malloc(sizeof(node));
if (newNode == NULL) {
fprintf(stderr, "Out of memory! Exiting.n");
exit(EXIT_FAILURE);
}
// Allocate memory to store n width data
newNode->data = malloc(strlen(name) + 1);
strcpy(newNode->data, name);
newNode->next = NULL;
// Create root node if no root exists
if (*root == NULL) {
*root = newNode;
return;
}
// Loop until end of linked list is found and insert data
node* temp = *root;
while (temp->next != NULL) {
temp = temp->next;
}
temp->next = newNode;
}
However, when I allocate a new node at the first line of AppendData
function, would I not override that allocation if my string data is say, of 1024 bytes or something like that? Because I need to calculate the string length dynamically with strlen
I believe this would cause an overflow?
How do I go abouts calculating just enough space and not overriding the linked list node?