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)); 
5
  • 1
    you do that by declaring the pointer as a pointer, and by not casting the return value of malloc(). Commented Feb 10, 2014 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. Commented Feb 10, 2014 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? Commented Feb 11, 2014 at 0:02
  • @TonyGW Well by writing exactly that sizeof(_object_t). Commented Feb 11, 2014 at 0:03
  • @Nabla, can I also write malloc(sizeof(object_ptr*)) ? It's important for me to hide the original structure name. thanks Commented Feb 11, 2014 at 0:04

2 Answers 2

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.)

Sign up to request clarification or add additional context in comments.

Comments

0

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.