Hey guys/girls/other.
got a quick question.
So I'm working on a personal project and I'm trying to make all my data structures general so that I can reuse them. My program is working fine, but I'm not actually sure if it is the correct way to go about it.
Details: So I have a linked list that looks something like this.
ADT
Code:
struct Node {
void *data;
struct Node *next;
} *List;
In 'my current' instance, void *data is going to be some text from a file.
How I'm getting the data for the ADT
Code:
List extracted_text_data(List self)
{
const unsigned short buffer_size = 31;
size_t len;
char buffer[buffer_size];
// TODO: prompt user for text location.
FILE *fp = fopen("./input.text", "r");
if (fp == NULL) {
perror("File error");
exit(EXIT_FAILURE);
}
while (fgets(buffer, sizeof(buffer), fp) != NULL) {
len = strlen(buffer) - 1;
// need to remove newline characters at the end, otherwise
// causes issues when traversing through the data in the linked list.
if(buffer[len] == '\n') {
buffer[len] = '\0';
}
self = insert(self, (void *) format_string(buffer, len), len);
}
fclose(fp);
return self;
}
Is this correct?
Code:
static List node_init(void *data, size_t size)
{
List new_node = malloc(sizeof(*new_node));
if (new_node == NULL) {
fprintf(stderr, "Error: allocating memory for new node.\n");
exit(EXIT_FAILURE);
}
// works, but is just allocating a chunk.. feel this could be better.
new_node->data = malloc(sizeof(size));
if (new_node->data == NULL) {
fprintf(stderr, "Error: allocating memory for data\n");
exit(EXIT_FAILURE);
}
memcpy(new_node->data, data, size);
new_node->next = NULL;
return new_node;
}
So, the issue is. I'm using a buffer which is 31 chars. The input might not need 31 chars so to save memory I get the size of the buffer to allocate memory for the void *data in my node init.
Bottom line is:
When using void *data how do you correctly allocate it memory to store whatever you are sending it after you've cast it to a void * type? I've just used the size of the char array to get the new strlen to allocate a block.
Or would a better approach be to pass a function pointer where you are actually allocating the correct type?
Some advice/resources would be cool!The whole project can be found here: https://github.com/daniel-k-richardson/PasswordGuesser