views:

207

answers:

3
#include <stdio.h>
#include <stdlib.h>

int main() 
{
     FILE *fp = fopen("lr.txt", "r");
     fseek(fp, 0L, SEEK_END);
     int size = ftell(fp);
     fseek(fp, 0L, SEEK_SET);

     char *lorem_ipsum;

     int i = 0;
     lorem_ipsum = (char*) malloc(sizeof(char) * size);
     while(fscanf(fp, "%s\n", lorem_ipsum) != EOF)
     {
      printf("%s", lorem_ipsum[i]);
      i++;

     }
     fclose(fp);
     return 0;
}

This program compiled and ran, however, what happened was that I got a segfault and I don't know quite exactly what's wrong with this program. Could somebody help me with the pointer error I got?

+6  A: 

You are trying to print lorem_ipsum[i] as if it were a string. lorem_ipsum is a string, so lorem_ipsum[i] is just a character.

The segfault happens because printf looks at the value of the character at lorem_ipsum[i] and interprets it as a char* pointer (a string). Naturally, the value of the character doesn't correspond to a valid, allocated memory address.

Tyler McHenry
The analysis is correct - but the code is misguided even when corrected. Since the size of the file was allocated, it would presumably make most sense to read it all in at once - for which fread() is more appropriate. The fscanf() function with %s is pretty weird, even if you use %*s.
Jonathan Leffler
I'm guessing the intention is to read lines from the file and allocating memory enough for the whole file will cater for very loooong lines.
Martlark
+3  A: 

You're passing a char (lorem_ipsum[i]) to the fscanf function, which expects a char* as the argument.

You might want to use lorem_ipsum or lorem_ipsum+i if you really want to strip the first i characters off.

jpalecek
A: 

Can you explain what you're trying to do in the for loop?

It seems to me that you are trying to read the file line by line and then print the line. However, when you do the printf("%s", lorem_ipsum[i]), you are sending a character, not a string.

Uri