1

I have the following struct and tried to use malloc to create a new object dynamically. It seems to work now with object_ptr obj_ptr1 = malloc(sizeof(object_ptr)); This only assigns the pointer size of object_ptr to obj_ptr1 ? but how do you assign the size of the original struct _object_t in this case?

typedef struct
{
   int struct_id;
   void *(*function)(void *);
   int status;
} _object_t;

typedef struct _object_t* object_ptr;

/* create a new object */
object_ptr obj_ptr1 = malloc(sizeof(object_ptr));
TonyW
  • 18,375
  • 42
  • 110
  • 183
  • 1
    you do that by declaring the pointer as a pointer, and by [***not*** casting the return value of `malloc()`](http://stackoverflow.com/questions/605845/do-i-cast-the-result-of-malloc/605858#605858). –  Feb 10 '14 at 23:50
  • 1
    After your edit: Now it is a pointer, but you are still allocating the wrong size. You are allocating for the size of a pointer to `struct _object_t`. Maybe you should use more telling names, like `struct object_t` and `object_ptr`. –  Feb 10 '14 at 23:59
  • thanks, I see that the malloc in my question only assigns the size of the object_ptr to obj_ptr1, but how to assign the size of original struct _object_t then? – TonyW Feb 11 '14 at 00:02
  • @TonyGW Well by writing exactly that `sizeof(_object_t)`. –  Feb 11 '14 at 00:03
  • @Nabla, can I also write malloc(sizeof(object_ptr*)) ? It's important for me to hide the original structure name. thanks – TonyW Feb 11 '14 at 00:04

2 Answers2

3

Typedefs for pointer types are often a bad idea, since they can make it difficult to tell whether a type name refers to a pointer type or not.

Suggestion:

typedef struct { /* ... */ } object_t;
object_t *obj1 = malloc(sizeof *obj1);

And if you want to allocate space for an array of N objects:

object_t *obj1 = malloc(N * sizeof *obj1);

Note that I've removed the leading underscore from the type name. Identifiers starting with underscores are reserved to the implementation; you shouldn't define them in your own code.

The malloc(sizeof *foo) idiom may take a little getting used to, but it means you don't have to specify the type name more than once, which avoids errors. (The *obj1 doesn't actually dereference obj1, since the operand of sizeof is not evaluated.)

In your code:

object_t obj1 = malloc(sizeof(object_t));

since object_t is a pointer type, you're allocating enough memory to hold a pointer object, not a structure object. (Using such similar names object_t and _object_t for the pointer and struct types, respectively, undoubtedly contributed to the confusion.)

Keith Thompson
  • 254,901
  • 44
  • 429
  • 631
0

The problem is in your malloc line. You must allocate sizeof(_object_t) not sizeof(object_t)

vad
  • 344
  • 2
  • 12