1

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?

25
  • 1
    Where is your int main(...);? Commented Dec 7, 2015 at 16:24
  • 1
    Why 3 in printf( "%s", (wordlist[3]) );? Commented Dec 7, 2015 at 16:25
  • 1
    Method used to determine fileLines will be 1 short if Wordlist does not end with '\n'. Commented Dec 7, 2015 at 16:27
  • 1
    @Eijomjo If file contains 3 words than you wordlist[3] will access index out of bounds and cause undefined behaviour . You can have valid indices 0 ,1 ,2 not 3. Don't access index 3 . Commented Dec 7, 2015 at 16:35
  • 1
    @Eijomjo And this information was necessary and was to be mentioned in question . Commented Dec 7, 2015 at 16:37

2 Answers 2

3

Incorrect usage of getline()

Pass address of size_t rather than 0.

for( c = 0; c < fileLines; c++ )
  // getline( &wordlist[c], 0, fp );
  size_t size = 0;
  getline( &wordlist[c], &size, fp );

To fix a potential off by 1 in line count calculation

int c;
size_t fileLines = 0;
int previous = '\n';
while ((c = fgetc(fp)) != EOF) {
    if( previous == '\n') fileLines++;
    previous = c;
}
Sign up to request clarification or add additional context in comments.

Comments

0

regarding this line:

printf( "%s", (wordlist[3]) );

It is trying to print the wrong line. and it is not part of the for() loop that is reading the lines from the file.

Suggest:

size_t lineLength = 0;
for( int i = 0; i < fileLines; i++ )
{
     getline( &(wordlist[i]), &lineLength, fp );
     printf( "%s\n", wordlist[i] );
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.