Yeah, this is once again one of these questions, I know the Internet is flooded with this particular problem, yet I couldn't find the solution to that problem in other threads, so here I am.
I'm getting the "realloc() invalid next size" error in this code which parses some text and puts individual words in the array of strings, argv. This code is very simple and there is a lot more to do to make this code better, I'm fully aware of it.
Anyway, I'm getting this error when I exceed some amount of reallocation of the char **argv variable. Funilly enough, it's dependent on the software I run it in. For example, using CLion, I get this error when I try to parse a text of 5 words and in Visual Studio, it's a text of 3 words when I get this error.
So here is the code, it takes 3 parameters, the first one is a string, a buffer where a text is located. The next 2 parameters are passed by reference, argc and argv respectively.
This is the call to the function:
char **argv = NULL;
int argc = 0;
//buffer is a string terminated with a zero
parse_line(buffer, &arc, &argv);
And this is the function:
int parse_line(char *buffer, int *argc, char ***argv) {
int arg_cap = 10;
*argv = malloc(sizeof(char*));
(*argv)[0] = malloc(arg_cap);
int index_iter = 0;
for (int i = 0; buffer[i]; i++) {
if (buffer[i] == ' ') {
(*argv)[*argc][index_iter] = 0;
(*argv)[*argc] = realloc((*argv)[*argc], index_iter+1);
index_iter = 0;
arg_cap = 10;
(*argc)++;
*argv = realloc(*argv, sizeof(char*) * (*argc));
(*argv)[*argc] = malloc(arg_cap);
}
else {
index_iter++;
if (index_iter >= arg_cap) {
arg_cap *= 2;
(*argv)[*argc] = realloc((*argv)[*argc], arg_cap);
}
(*argv)[*argc][index_iter-1] = buffer[i];
}
}
(*argv)[*argc][index_iter] = 0;
(*argv)[*argc] = realloc((*argv)[*argc], index_iter+1);
(*argc)++;
return 1;
}
I hope you can figure out what the problem is. Thank you, guys.
The line:
*argv = realloc(*argv, sizeof(char*) * (*argc));
Should be:
*argv = realloc(*argv, sizeof(char*) * (1 + *argc));
After the first argument has been inserted, and *argc
has been incremented, your code will realloc
the array to hold only one pointer, when you now need two.