I've been facing this error for quite some time now, and I'm stuck here. I was creating a function that converts a sentence into an array of words, before processing them further, but the problem is that realloc is not looping more than 3 times. I.e., if i use a string of 3 words, the code runs fine, but if the sentence is more than 3 words, I'm stuck on this error
realloc(): invalid next size
zsh: IOT instruction ./a.out
Here is my code
#include <stdio.h>
#include <string.h>
#include <stdbool.h>
#include <stdlib.h>
char **process_str(char *str)
{
char **str_ptr, **str_ptr2, *word_ptr, word[20], chr;
int i = 0, count = 0, ind = 0, len;
bool first = true;
if (str == NULL) return (NULL);
str_ptr = (char **)malloc(sizeof(char *));
if (str_ptr == NULL) return (NULL);
len = strlen(str) + 1;
while (i < len)
{
chr = str[i];
if ((chr == ' ' || chr == '\0') && ind > 0)
{
word[ind] = '\0';
word_ptr = strdup(word);
if (first)
{
*(str_ptr) = word_ptr;
first = false;
}
else
{
str_ptr2 = (char **)realloc(str_ptr, count + 1);
if (str_ptr2 == NULL) return (NULL);
*(str_ptr2 + count) = word_ptr;
str_ptr = str_ptr2;
}
ind = 0;
count++;
i++;
continue;
}
if (chr != ' ')
{
word[ind] = chr;
ind++;
}
i++;
}
str_ptr2 = (char **)realloc(str_ptr, count + 1);
if (str_ptr2 == NULL) return (NULL);
*(str_ptr2 + count) = NULL;
str_ptr = str_ptr2;
return (str_ptr);
}
and i tested it using this function
int main(void)
{
int i = 1;
char **ptr, *s_ptr;
char *str = "please please anf dsd it for";
ptr = process_str(str);
printf("done step one\n");
if (ptr == NULL)
{
printf("ptr is NULL");
return (1);
}
s_ptr = ptr[0];
while (s_ptr != NULL)
{
printf("String: %s\n", s_ptr);
s_ptr = ptr[i];
i++;
}
return (0);
}
if i change the value of str
in main, to something like str = "This is home"
the code executes fine.
Please any help is appreciated.