c - 简单地创建一个数据结构,它怎么会发生段错误?

标签 c data-structures segmentation-fault malloc

我有一个关于数据结构的简单程序,但它会出现段错误,这让我非常沮丧,因为我完全不知道为什么。任何人都可以指出有关此代码的任何内容(甚至不相关)吗?谢谢

#include <unistd.h>
#include <stdlib.h>

typedef struct prof
{  
    struct prof *next;
    char c;
    int x;
    int y;
} profile;

profile *create_profile(char c, int i, int j)
{
    profile *new_elem;
    new_elem = (profile*)malloc(sizeof(profile));
    if (new_elem == NULL)
        return (NULL);
    new_elem->next = NULL;
    new_elem->c = c;
    new_elem->x = i;
    new_elem->y = j;
    return (new_elem);
}

int main()
{
    profile **king = NULL;
    *king = create_profile('K', 1, 1);
    return 0;
}

最佳答案

你的国王是一个指向结构指针的指针。 您需要一些地方来存储指向结构的指针,但那是您没有分配的地方。
您可以引入一个指针来解决这个问题。

int main()
{
    /* introduce and NULL-init a pointer to struct */
    profile* prince = NULL;
    /* actually the init to NULL is not necessary,
       because prince gets initialised later indirectly via king
       (credits to alk), but it does not hurt and initialising everything
       is a good habit. */ 

    /* Introduce a pointer to pointer to struct,
       initialised with the address of above pointer to struct,
       the address of the above variable "prince" to be precise and clear.
       The space for that automatic local variable is not dynamic,
       it does not require a malloc. */
    profile **king = &prince;

    /* what the king is pointing to, i.e. the prince,
       gets assigned what the function returns,
       which is a cleanly allocated pointer to a new struct. */
    *king = create_profile('K', 1, 1);

    /* if king were still NULL, above statement would try to write
       (the cleanly allocated pointer) into memory by dereferencing NULL ... 
       segfault! 
       (Well not necessarily, as alk points out, credits.
       But dereferencing NULL is undefibed behaviour,  
       an almost guaranteed way to trouble in the long run
       and in case a seggault is observed, a likely explanation.
     */ 
    return 0;
}

关于c - 简单地创建一个数据结构,它怎么会发生段错误?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51800613/

相关文章:

c - sprintf 的段错误

c - Windows : Connect TI-Launchpad to Amazon Web Services

c - C 中基本基数特里树的实现

c - Ruby、ioctl 和复杂结构

java - 给定整数集的子集,其和为常量 N : Java

data-structures - BFS和DFS的运行时间解释

c - 指针&字符段错误

代码崩溃并出现错误段错误(核心转储)

python - 如何使用 Python C API 从对象的方法访问常量?

c - 在图中删除/插入顶点时出现问题