Please help me find an error in dynamic memory allocation.
It is necessary to print all the words that begin and end with one letter.
The algorithm works with a static array, but there is an error when trying to create a dynamic array.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main()
{
int len = 0;
char str[10] = "aba cd geg ";
char* word = NULL;
int j = 0;
int i = 0;
int n = 0;
while(str[i]!='\0')
{
if(!isspace(str[i]))
{
n++;
word = (char*)realloc(word, (n* sizeof(char)));
word[j] = str[i];
j++;
len++;
}
else
{
if(word[0] == word[len-1])
{
j = 0;
while(j < len)
{
printf("%c", word[j]);
j++;
}
}
j = 0;
len = 0;
free(word);
n = 0;
}
i++;
}
return 0;
}
#include <ctype.h>. Compile with all warnings enabled and consider them as errors. Andchar str[10] = "aba cd geg ";, there is not enough space instryou forgot about the NUL string terminator, just usechar str[] = "aba cd geg ";and let the compiler figure out the required size. There may be more errors though.word = (char*)realloc(word, (n* sizeof(char)));1) in C, the returned type isvoid*which can be assigned to any pointer. Casting just clutters the code. Suggest removing that cast. 2) When callingrealloc(), always assign to a temp variable. Then check (!=NULL) and if not NULL, then assign to the target variable. Otherwise, the original pointer is lost, resulting in a memory leak. 3) the parameter is expected to be of typesize_t, notint, so this statement:int n=0;should be:size_t n=0;gcc, at a minimum use:-Wall -Wextra -Wconversion -pedantic -std=gnu11) Note: other compilers use different options to produce the same results