Вопрос

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.

Это было полезно?

Решение

typedef struct _entity {
    int value;
} *Entity;
  ^
  ^

You probably don't want this *. Otherwise, you are typedef-ing Entity to be a pointer to a struct, rather than a struct. So your code would become:

typedef struct _entity {
    int value;
} Entity;


Entity *new_entity(void) {
    Entity *ptr = malloc(sizeof(*ptr));
    assert( ptr );

    ptr->value = 5;

    return ptr;
}

If, for some reason, you do want Entity to 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:

Entity *ptr = malloc(sizeof(*ptr));  // Allocate an Entity
*ptr = malloc(sizeof(**ptr));        // Allocate a *Entity

But there's almost certainly no need to do this.

Другие советы

you shouldn't use both * and ->, one of them is enough

ptr->value = 5 

OR

(*ptr).value = 5
Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top