0

I'm suppose to read a file and then write to the file in an alphabatically sorted array. However, I am keep getting a segmentation fault using gdb, indicating my display and sort function occur segmentation fault.

EDIT: I fixed it by use a macro to allocate memory. Since it is an assignment, I do not wish to disclose it just in case. I do appreciate everyone's help on my code.

3
  • Could you maybe be a bit more generous w/ the comments? And while you're at it, the indentation? Thanks. Commented Nov 14, 2012 at 0:11
  • Can you provide a core dump of your binary compiled with symbols? Commented Nov 14, 2012 at 0:22
  • Add the output of running bt in gdb to the question. Commented Nov 14, 2012 at 0:22

1 Answer 1

1

You're supposed to do this? Ouch.

I got a segfault too, but in read_names(). I was able to fix it by replacing all the strtok() stuff with a simple scanf():

    void read_names (FILE *fp, char **f, char **l, char *m, int num)//read it
    {
        int i=0;
        char temp[80];

        for (i=0; i<num; i++)
        { 
            fscanf( fp, "%s %s %s", f[i], l[i], m);
        }
    } 

After that I was able to sort & print, though it's trying to free() something erroneously at the end.

I general strtok() is insecure and just a pain - it destroys your string.

Also, more meaningful names make it easier to work with. I eventually figured out that "l[]" was an array of strings containing the last name, but something along the lines of "sLastName[]" would have sped that up immensely.

EDIT:

I gathered your input text file looked like this:

2 bill smith a doug adams r

EDIT2:

OK, found another segfault. What is "num"? It seems to be interpreted as kindof the number of names in the file and kindof the size of each name?

// allocate "num" first name elements -> implied "num" is # of names
f=(char**)malloc (num*sizeof(char*));

// allocate space for each name... but uses the value of "num" for each name
for (i=0; i<num;i++)
    f[i]=(char*)malloc (num*sizeof(char));  // "num" bytes per name?

When I started allocating 100 bytes per name instead of the value of "num", the second - and for me last - segfault went away.

Did you enter the entire program and then start testing? It would be a lot easier to get it working in small steps then incrementally adding functionality - verifying with debugger and/or printf() that it's doing what you want at each step.

Sign up to request clarification or add additional context in comments.

1 Comment

I fixed it. instead of using num, I suppose to use a macro for those ones inside the loop. Thanks everyone for the input. I appreciate it.

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.