这与C中的这两个程序有什么不同

pep*_*ero 0 c pointers function segmentation-fault

我有两个非常相似的程序,如下所示.

程序A:运行时没问题,

#include <string.h>
#include <stdio.h>

typedef struct p_struct{
   unsigned char* pulist;
   int length;
} list_type;

int get_struct(list_type* l)
{
   memset(l->pulist, 0, 4); 
   l->length=4;
}

int main ()
{
   list_type str;
   get_struct(&str);
}
Run Code Online (Sandbox Code Playgroud)

程序B:有一个额外的函数调用,仍然编译,但崩溃与运行时错误"分段错误"与gcc.

#include <string.h>
#include <stdio.h>

typedef struct p_struct{
   unsigned char* pulist;
   int length;
} list_type;

int get_struct(list_type* l)
{
   memset(l->pulist, 0, 4); 
   l->length = 4;
}

int get_struct_a()
{
   list_type str;
   get_struct(&str);
}

int main ()
{
   get_struct_a();
}
Run Code Online (Sandbox Code Playgroud)

我真的很想弄清楚这里的问题.任何人都可以告诉我导致"分段错误"的原因是什么?另外,为什么程序B给出"分段错误"错误,而程序A没有?

Vic*_*cky 5

您没有为pulist结构成员分配内存.因此,当你memset它,你在其他地方覆盖其他一些内存.幸运的是,在第二种情况下,您覆盖的内存不会产生段错误,但您仍在破坏内存.