I have two very similar programs, as follows.
Program A: no problem when running,
#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);
}
Program B: has an additional function call, still compiles, but crashes with run-time error “Segmentation fault” with 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();
}
I am really struggling to figure out the problem here. Can anyone tell me what causes “Segmentation error”? Also, why program B gives “Segmentation fault” error, while program A does not?
You’re not allocating memory for the
pulistmember of your structure. Hence when youmemsetit, you’re overwriting some other memory somewhere else. It’s just luck that in the second case the memory you overwrite happens not to give a segfault, but you’re still corrupting the memory.