So, I’m trying to write a function which return a pointer to an ADT, in the heap.
The problem is that I can’t manipulate it after the memory allocation. Here is a simplified code
typedef struct _entity {
int value;
} *Entity;
Entity *new_entity() {
Entity *ptr = (Entity*)malloc(sizeof(struct _entity));
assert( ptr );
(*ptr)->value = 5; // program crashes after this line
return ptr;
}
The error is:
Unhandled exception at 0x013e1665 in test.exe: 0xC0000005: Access
violation writing location 0xcdcdce21.
You probably don’t want this
*. Otherwise, you are typedef-ingEntityto be a pointer to a struct, rather than a struct. So your code would become:If, for some reason, you do want
Entityto be a pointer type, then the rest of your code is wrong. You’ve malloced some space for the pointer, but not for what it’s pointing to. It would need to be more like this:But there’s almost certainly no need to do this.