Reputation: 4878
I wrote a program that automatically allocates memory for a structure and then sets a field within that structure equal to zero.
I thought, instead of setting only that member equal to zero, why not zero-out the entire block? In comes memset()
.
After using this function my program no longer worked. Once I attempted to assign a value to a field within the structure contained in that memory block the program crashed with a segmentation fault error.
So, this leads me to wonder - when a block of memory is allocated via malloc()
/AUTO, is there other information stored in this location that is necessary for accessing and using this space?
typedef struct{
NodeT *nodes[MAX_SIZE];
int count;
} stackT;
stackT stack;
stackT* ptr = &stack;
void init(stackT* stackPtr){
//stackPtr->count = 0;
memset(stackPtr, 0, sizeof(stackptr));
}
Upvotes: 1
Views: 2123
Reputation: 4666
Please do a memset by passing the size of the structure and not size of the pointer:
memset(stackPtr, 0, sizeof(stackT));
Having said that, malloc would return a pointer to the address block (let us say of N bytes). Next, you need to pass the same pointer to memset and the size N.. The pointer returned by malloc does not contain any other information that can be affected by doing a memset.
Upvotes: 5
Reputation: 225281
memset(stackPtr, 0, sizeof(stackptr));
This is taking the size of the pointer; the first element of nodes
will be zeroed, not count
. Use sizeof(*stackptr)
or sizeof(stackT)
.
Upvotes: 4
Reputation: 67355
malloc()
does indeed store information about the size of a block of memory it returns.
However, memset()
does not know or care about the size. memset()
will blindly write to the specified address for the number of specified bytes, regardless of what it might be overwriting. It is up to the programmer to ensure that only valid memory is written to.
And now that you've decided to post your code, I see you mistakenly use sizeof(stackptr)
for the size instead of sizeof(stackT)
. The version you use is using the size of the pointer rather than the size of the data structure.
Upvotes: 3
Reputation: 122458
memset()
is the right function to use:
#include <string.h>
#include <stdbool.h>
typedef struct {
char name[30];
int age;
bool isMale;
} MyStruct;
MyStruct *myStruct = (MyStruct *)malloc(sizeof(MyStruct));
memset(myStruct, 0, sizeof(MyStruct));
The reason your code doesn't work as expected is because sizeof(stackptr)
is the size of the pointer, not the struct
.
Upvotes: 3