So, my goal was to define a struct in which there is -
- A command name (e.g. - "print")
- Command arguments counter
- A strings array containing the arguments.
You can review my code, but I'm really having a hard time understanding what am I doing wrong -
- I use malloc to dynamically set my_struct.command size
- I use malloc to dynamically set my_struct.arguments array size
- I use realloc to dynamically increase my_struct.arguments size for every argument I set
- I use malloc to dynamically set my_struct.arguments[i] size
- I finally call cleanup(), to free any dynamically assigned pointers.
I keep getting LOTS of memory leaks. But I cannot understand why.
Help and tips will be kindly appreciated.
#include <stdio.h>
#include <stdlib.h>
struct {
char *command;
int arguments_count;
char **arguments;
} my_struct;
void cleanup(void);
int main() {
int i;
my_struct.command = (char *)malloc(6*sizeof(char));
my_struct.command = "print";
my_struct.arguments_count = 1;
my_struct.arguments = (char **)malloc(sizeof(char *));
my_struct.arguments[0] = "hello";
for(i = 1 ; i < 10; i++) {
my_struct.arguments = (char **)realloc(my_struct.arguments, sizeof(char *)*(i+1));
my_struct.arguments[i] = (char *)malloc(8*sizeof(char));
my_struct.arguments[i] = "hello";
my_struct.arguments_count++;
}
printf("Arguments count is: %d\n", my_struct.arguments_count);
printf("The arguments are:\n");
for(i = 0; i < 10; i++) {
printf("%s\n", my_struct.arguments[i]);
}
cleanup();
exit(0);
}
void cleanup(void) {
int i;
for(i = 0; i < 10; i++)
free(my_struct.arguments[i]);
free(my_struct.arguments);
free(my_struct.command);
}
my_struct.command = (char *)malloc(6*sizeof(char)); my_struct.command = "print";
That right there is a leak! – Kevinsizeof(char)
– vmtarg[i] = malloc(8*sizeof(char)); arg[i] = "hello";
-- That's a memory leak. You reserve memory, but immediately lose the handle to it by assigning to a string literal. The string literal isn't something you canfree
later, either. – M Oehmstrcpy
to copy a string to a char array. – Matheus Rossi Saciottostrcpy(my_struct.command, "hello");
– Matheus Rossi Saciotto