Update: Still none explained how to fix the problem with sizeof()
I wrote the following function in C99:
Explanation: the function gets an array of pointers with a length of size and fills it with words from the user input (World's length is >1 for sure).
Example of an input: Wish you great holiday
the code which is written inside Allocating Exact Size To The Extended Word
block is to make my code a little more efficient and to allocate the exact size of memory for each world instead of assigning memory for the maximum string length.
The problem is that my code fails when testing it because of accessing a place of memory which I should not touch. can you help me fix that?
The error is probably caused by one of the code lines inside the Allocating Exact Size To The Extended Word
block.
#define WORDS_ARRAY_SIZE 100
#define MAX_STR_LEN 50
int read_words(char* words[], int size, int max_str_len)
{
int i,j;
bool Stop=false;
for (i=0;i<size && !Stop;++i)
{
char tmp[1], ch, *word=tmp;
for (j=0;j<max_str_len;++j)
{
if (scanf("%c",&ch)==EOF)
{
Stop=true;
break;
}
if (ch==' ')
break;
word[j]=ch;
//Allocating Exact Size To The Extended Word
char* TmpExtendedword=malloc((i+2)*sizeof(char));
if (TmpExtendedword==NULL)
{
free(TmpExtendedword);
return -1;
}
strcpy(TmpExtendedword,word);
word=malloc((i+2)*sizeof(char));
if (word==NULL)
{
free(word);
return -1;
}
strcpy(word,TmpExtendedword);
//
}
word[j]='\0';
words[i]=word;
}
return i;
}
int main()
{
int num_words =0;
char* words[WORDS_ARRAY_SIZE];
num_words = read_words(words, WORDS_ARRAY_SIZE, MAX_STR_LEN);
}
Small note:
how could I give the pointer word
an initial size of 1 instead of pointing to an array which I will never use tmpword
?