Segmentation Fault

This is a discussion on Segmentation Fault within the C Programming forums, part of the General Programming Boards category; I am getting a core dump when I try scanning in the values. Please help. Code: #include <stdio.h> #include <string.h> ...

  1. #1
    Registered User
    Join Date
    Jul 2005
    Posts
    1

    Segmentation Fault

    I am getting a core dump when I try scanning in the values. Please help.
    Code:
    #include <stdio.h>
    #include <string.h>
    int main()
    {
            char *strings[50];
            int amnt;
            printf("Enter the number of strings (0 to 50)\n> ");
            scanf("%d",&amnt);
            printf("Enter %d strings on separate lines\n",amnt);
            int i =0;
    for (i=0;i<amnt;i++)
            {
                    scanf("\n%s",strings[i]);
            }

  2. #2
    C++ Witch laserlight's Avatar
    Join Date
    Oct 2003
    Location
    Singapore
    Posts
    21,739
    For starters, you never allocated any memory for the strings.
    C + C++ Compiler: MinGW port of GCC
    Version Control System: Bazaar

    Look up a C++ Reference and learn How To Ask Questions The Smart Way

  3. #3
    and the Hat of Guessing tabstop's Avatar
    Join Date
    Nov 2007
    Posts
    14,185
    Just because you have a pointer somewhere, doesn't mean you own the memory it is pointing to. In this case, you have 50 pointers that don't point anywhere, but you try to use them anyway. You will need memory for each of those pointers (either malloc in a loop, or a 2D character array seem like your options here).

  4. #4
    Registered User slingerland3g's Avatar
    Join Date
    Jan 2008
    Location
    Seattle
    Posts
    602
    What you will need to do is allocate space for your pointer, say malloc for 25 chars, right before your scanf assignment.

    To check that your strings were inserted, you can create another 'for loop' to cycle through your array of strings.


    Then you will need another for loop to free those malloc calls, or you will cause a memory leak further on down the road......lots of fun.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Segmentation fault problem
    By odedbobi in forum Linux Programming
    Replies: 1
    Last Post: 11-19-2008, 02:36 AM
  2. Segmentation fault
    By bennyandthejets in forum C++ Programming
    Replies: 7
    Last Post: 09-07-2005, 05:04 PM
  3. Segmentation fault
    By NoUse in forum C Programming
    Replies: 4
    Last Post: 03-26-2005, 02:29 PM
  4. Locating A Segmentation Fault
    By Stack Overflow in forum C Programming
    Replies: 12
    Last Post: 12-14-2004, 12:33 PM
  5. Segmentation fault...
    By alvifarooq in forum C++ Programming
    Replies: 14
    Last Post: 09-26-2004, 12:53 PM

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21