简体   繁体   中英

Error in the program with structures -segmentation fault

    #include <stdio.h>

    struct p

    {
        char *name;
        struct p *next;
    };

    struct p *ptrary[10];

    int main()
    {
        struct p p, q;
        p.name = "xyz";
        p.next = NULL;
        ptrary[0] = &p;
        strcpy(q.name, p.name);
        ptrary[1] = &q;
        printf("%s\n", ptrary[1]->name);
        return 0;
    }

The program is giving segmention fault on execution. What is wrong here? Do I need to allocate memory for ptrary?

You will have to allocate some memory before using it.

q.name = malloc(10);
strcpy(q.name, p.name);

Edit: As correctly pointer out by unwind, sizeof char will be always 1. Hence removing from malloc .

You need to allocate room for the string, before using strcpy() . You're trying to copy a new string into memory that is holding a string initialized from a string literal, which is totally invalid. Such strings should be considered read-only.

You can avoid this problem by copying the pointer, which will then copy the string created by the string literal:

q.name = p.name;
struct p
{
    char *name;  //name points nowhere
    struct p *next;
};

strcpy(q.name, p.name); // q.name is any arbitrary value

Allocate memory for name before using it.

OR declare as:

struct p
{
    char name[4];  //the number of characters you require
    struct p *next;
};
#include <stdio.h>

    struct p

    {
        char name[10];
        struct p *next;
    };

    struct p *ptrary[10];

    int main()
    {
        struct p p, q;
        strcpy(p.name , "xyz");
        p.next = NULL;
        ptrary[0] = &p;
        strcpy(q.name, p.name);
        ptrary[1] = &q;
        printf("%s\n", ptrary[1]->name);
        return 0;
    }

or you can use p.name = malloc(sizeof(char)*10);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM