SynAck
SynAck

Reputation: 426

Runtime error sorting a linked list of strings

void sort(struct node **s2) {
    struct node *x, *y;
    x = *s2;
    char *str;
    while (x != NULL) {
        y = x->n;
        while (y != NULL) {
            if (strcmp(x->name, y->name) > 0) {
                strcpy(str, x->name);
                strcpy(x->name, y->name);
                strcpy(y->name, str);
            }
            y = y->n;
        }
        x = x->n;
    }
}

This is showing a run time error. I don't know whats wrong I believe the sorting is correct It's selection sort The structure of my node is:

struct node {
    char *name;
    struct node *n;
};

It's showing runtime error.

Upvotes: 2

Views: 85

Answers (2)

Shailesh
Shailesh

Reputation: 11

char *str; This statement only create a pointer. There is no memory is associated with that;

strcpy(char* dest, char* src) simply copies the the content in the memory pointed by src to memory point by dest

In your case str not pointing to any memory location;

strcpy(str, x->name)

since str pointing to nothing, this statement endup with an error because strcpy fails to copy to str

instead of char* str; use char str[SIZE_MAX];

Upvotes: 1

chux
chux

Reputation: 154127

char *str; ... strcpy(str,x->name); copies data pointed to by name to an someplace (it is undefined behavior) as str is an uninitialized pointer.

Just swap pointers.

       if (strcmp(x->name,y->name) > 0) {
         char *temp = x->name;
         x->name = y->name;
         y->name = temp;
       }

Upvotes: 5

Related Questions