I am not an expert with C by any means and I need some assistance.
When I run this code it crashes and says that realloc has an invalid next size.
This issue is most likely related to the new_command function but I cant figure it out.
Please help me /g/ I need to learn (I would post in wsr but they dont have code tags)
Pls no bully.
#define _GNU_SOURCE
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
typedef struct
{
char* alias;
void (*function)();
}command;
command* global_commands;
int total_commands = 0;
void echo()
{
puts("hello");
}
void execute(char* command_alias)
{
for(int current_command = 0; current_command < total_commands; current_command++)
{
if(!strcmp(global_commands[current_command].alias, command_alias))
{
puts("Exists, running...");
global_commands[current_command].function();
break;
}
}
}
void new_command(char* new_alias, void* new_function)
{
command new_command = {new_alias, new_function};
if(!(global_commands = realloc(global_commands, sizeof(global_commands) + sizeof(new_command))))
{
puts("Unable to add command!");
return;
}
global_commands[total_commands] = new_command;
total_commands++;
}
char* getstr()
{
char* str = calloc(sizeof(char), 1);
char character;
while((character = getchar()) != '\n')
asprintf(&str, "%s%c", str, character);
return str;
}
int main()
{
if(!(global_commands = malloc(sizeof(command))))
{
puts("Failed to allocate space for command list!");
return 1;
}
fprintf(stdout, "> ");
new_command("exit", echo);
new_command("test", echo);
new_command("cd", echo);
for(;;)
{
char* command_alias = getstr();
execute(command_alias);
free(command_alias);
fprintf(stdout, "> ");
}
}