I'm trying to create a dynamically allocated array with dynamically allocated string elements, using getline().
This is my code,
char** getWordlist()
{
FILE* fp = fopen( "Wordlist", "r" );
if( errno == ENOENT )
fp = fopen( "Wordlist", "w+r" );
if( !fp ) {
perror( "Could not open wordlist" );
exit(EXIT_FAILURE);
}
int c, fileLines = 0;
do{
c = fgetc(fp);
if( c == '\n')
fileLines++;
} while( c != EOF );
rewind(fp);
char** wordlist = calloc( fileLines, sizeof(char*) );
for( c = 0; c < fileLines; c++ )
getline( &wordlist[c], 0, fp );
printf( "%s", (wordlist[0]) );
fclose(fp);
return wordlist;
}
However, printf prints outputs (null), so the strings was never created I think.
What am i doing wrong?
int main(...);?3inprintf( "%s", (wordlist[3]) );?fileLineswill be 1 short ifWordlistdoes not end with'\n'.wordlist[3]will access index out of bounds and cause undefined behaviour . You can have valid indices0 ,1 ,2not3. Don't access index3.