Thread: im not understanding what is wrong ... please notify me my mistake

  1. #1
    Registered User
    Join Date
    Aug 2008
    Posts
    46

    im not understanding what is wrong ... please notify me my mistake

    what is wrong in this program... its giving segmentation fault......

    Code:
    #include <stdio.h>
    
    main()
    {
    	FILE *fp;
    	char *ch;
    	int n;
    
    	if((fp = fopen("./stuf", "r+")) != NULL)
    		printf("no problem\n");
    	else
    		printf("problem\n");
    	while(fread(ch, 1, 1, fp)) {
    		printf("not entering\n");
    		printf("%c\n", *ch);
    	}
    }

  2. #2
    Hurry Slowly vart's Avatar
    Join Date
    Oct 2006
    Location
    Rishon LeZion, Israel
    Posts
    6,788
    1. main should be
    int main(void) - read FAQ
    2. when fopen failed you continue to the read part anyway
    3. ch is uninitialized pointer to char - you cannot write where (you do not know where it points

    better use
    char ch;
    fread(&ch,1,1,fp);

    4. for reading just one char fgetc seems to be more suitable
    All problems in computer science can be solved by another level of indirection,
    except for the problem of too many layers of indirection.
    – David J. Wheeler

  3. #3
    and the hat of sweating
    Join Date
    Aug 2007
    Location
    Toronto, ON
    Posts
    3,545
    Well 3 problems...
    First, if fopen() fails, you just print an error message and then continue trying to read from a bad file handle.
    Second, in this line:
    Code:
    while(fread(ch, 1, 1, fp))
    ch is a char* pointer, but you never malloc any space for it, but instead just use it as if it were a valid pointer, then on top of that you de-reference the bad pointer here:
    Code:
    printf("&#37;c\n", *ch);
    Edit: Oh, vart beat me to it, and yeah, main() should return an int.
    "I am probably the laziest programmer on the planet, a fact with which anyone who has ever seen my code will agree." - esbo, 11/15/2008

    "the internet is a scary place to be thats why i dont use it much." - billet, 03/17/2010

  4. #4
    Registered User
    Join Date
    Aug 2008
    Posts
    46
    thank you i got it....

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. God
    By datainjector in forum A Brief History of Cprogramming.com
    Replies: 746
    Last Post: 12-22-2002, 12:01 PM
  2. Whats wrong?
    By Unregistered in forum C Programming
    Replies: 6
    Last Post: 07-14-2002, 01:04 PM
  3. What did i do wrong? Code inside
    By The Rookie in forum C Programming
    Replies: 2
    Last Post: 05-18-2002, 08:14 AM
  4. Perhaps someone can see where i am wrong?
    By laree in forum C++ Programming
    Replies: 6
    Last Post: 02-13-2002, 12:47 AM
  5. what I'm I doing wrong?
    By Unregistered in forum C Programming
    Replies: 6
    Last Post: 02-03-2002, 02:46 AM