Thread: segmentation error

  1. #1
    Registered User
    Join Date
    Dec 2009
    Location
    Galle, Sri Lanka
    Posts
    3

    segmentation error

    Code:
    void new_friend(){
    	char *name;
    	char *phone;
    	char *email;
    	
    	printf("\n------New friend info------\n");
    	printf("Name: ");
    	scanf("%s", name);
    	printf("Phone-No: ");
    	scanf("%s", phone);
    	printf("e-Mail: ");
    	scanf("%s", email);
    	
    	printf("KALPA");
    	
    	write_to_file(name, phone, email);
    }
    this code block results in a segmentation error and it does not prompt the user for phone no also. It prompts only for the name and email.

    Why is this?

    But if character arrays are used instead of character pointers, it works. Why is this?

  2. #2
    Registered User
    Join Date
    Dec 2009
    Posts
    3
    The pointers name, phone and email don't point to allocated memory, that's why you are getting seg error. You must allocate memory before using it by writing
    Code:
    char name[30]; etc.
    or (alternatively) declare the char pointers as you have done already, but don't forget to give them usable addresses with malloc() before using them for storage.

    Put getchar() after every scanf to eat up the trailing '\n' that is left in the input buffer when you press enter.
    Last edited by zvn; 12-13-2009 at 03:23 AM.

  3. #3
    Registered User
    Join Date
    Dec 2009
    Location
    Galle, Sri Lanka
    Posts
    3
    Thanks

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. LDAP Query
    By Travoiz in forum C++ Programming
    Replies: 0
    Last Post: 08-13-2009, 02:58 PM
  2. Testing some code, lots of errors...
    By Sparrowhawk in forum C Programming
    Replies: 48
    Last Post: 12-15-2008, 04:09 AM
  3. how do you resolve this error?
    By -EquinoX- in forum C Programming
    Replies: 32
    Last Post: 11-05-2008, 04:35 PM
  4. Another syntax error
    By caldeira in forum C Programming
    Replies: 31
    Last Post: 09-05-2008, 01:01 AM
  5. Dikumud
    By maxorator in forum C++ Programming
    Replies: 1
    Last Post: 10-01-2005, 06:39 AM