Calling memset causes segmentation fault Calling memset causes segmentation fault unix unix

Calling memset causes segmentation fault


FilesStruct *old_dir;memset(old_dir,0,sizeof(FilesStruct));

attempts to write to an uninitialised pointer. This results in undefined behaviour, including possibly a crash. Its just luck (good or bad, depending on how you look at it) that the first instance of this behaviour didn't crash.

You need to allocate memory for old_dir. The easiest way to do this is to declare it on the stack

FilesStruct old_dir;memset(&old_dir,0,sizeof(old_dir));

or you could dynamically allocate on the heap (making sure to call free when you no longer need the object)

FilesStruct *old_dir = calloc(1, sizeof(*old_dir);/* use old_dir */free(old_dir);

The same applies to new_dir further down your code.


Neither old_dir nor new_dir are initialized, so this is undefined behavior. One solution would be to allocate both variables on the stack:

FilesStruct old_dir;//...FilesStruct new_dir;

and use the & operator to obtain the address when calling memset:

memset(&old_dir,0,sizeof(FilesStruct));


FilesStruct *old_dir;

This defines a FilesStruct pointer. It is uninitialized, so it doesn't actually point to any storage for a FilesStruct.

memset(old_dir,0,sizeof(FilesStruct));

Will tell memset to zero out whatever old_dir points at, but as the pointer is uninitialized, you get undefined behavior.

You'll need to provide storage for your pointer, e.g.

FilesStruct *old_dir = malloc(sizeof(FilesStruct));

In your case you don't really need a pointer or dynamically allocated memory, you might do

FilesStruct old_dir;memset(&old_dir,0,sizeof(FilesStruct));old_dir.x = 3;old_dir.text = 'c';printf("old dir: %d,%c\n",old_dir.x,old_dir.text);