silver surfer
silver surfer

Reputation: 258

Is there a difference in the way memory is zeroed by calloc and memset?

suppose i have a structure :

typedef struct
{
   int a;
   struct x;
   struct *x2;
   char *s;
}global_struct;

I have a pointer which points to the memory equal to size of structure :

ptr = calloc(sizeof(global_struct),1);

I actually don't want to allocate memory on the heap and so id declare a variable of the structure as :

global_struct var_struct1;

and i am using memset to initialize the memory to zero.

memset(&var_struct1,0,sizeof(var_struct1))

My code gives segmentation fault when i do this.

I want to know if there's any reason as to why would this fail and under what scenarios?

Upvotes: 1

Views: 190

Answers (2)

EvilTeach
EvilTeach

Reputation: 28872

There can be a difference. On a vms system, one of the idle time things that can happen is pages in the free list can be zeroed, and moved to a zeroed free list, so that some of the cost behind that calloc may be hidden. Your milage may vary.

Upvotes: 0

Lundin
Lundin

Reputation: 214310

Is there a difference in the way memory is zeroed by calloc and memset?

No. In fact, calloc likely calls memset internally.

I want to know if there's any reason as to why would this fail and under what scenarios?

No. You have the order of the calloc parameters wrong, it should be calloc(1, sizeof(global_struct));. Although in this case, the ordering of the parameters actually does not matter.

My code gives segmentation fault when i do this.

The problem is likely elsewhere in the code.

Upvotes: 3

Related Questions