Skip to main content
gamedev.net
🔒 Locked

Memory allocation

Started by Draigan 4 replies 200+ views
Original Post
Draigan
Draigan
I have a simple structure that that''s something like this:
  
typedef struct {
  int a;
  int b;
  vector<int> coll;
} MY_STRUCT;
  
When I allocate a block of these using the new operator:
  
MY_STRUCT* pStruct = new MY_STRUCT[100];
  
the constructor for the vector gets called and I can add stuff to it no problem. If I allocate a block of them using malloc:
  
MY_STRUCT* pStruct = (MY_STRUCT*)malloc(sizeof(MY_STRUCT) * 100);
  
then the constructor for the vector doesn''t get called. Is there a way to auto-initialize these vectors when using stuff like this? And how would I go about doing this? The problem is in the second case, I can''t add stuff to the vector since it isn''t initialized.
EvilTachikoma
EvilTachikoma
Why do you need to use malloc at all ? Its a C function that is not compatible with C++ in all cases, it only allocates the size of a given structure or class, but does not call the constructors or destructors... I say just use new... I am afraid to even imagine what would happen if you would free the memory without calling any desturctors, I think the behavior in this case would be undefined and depending on the system some kind of mess would come about .
Draigan
Draigan
Well, the thing is that I''m writing a memory manager and under the hood it uses malloc...
Zipster
Zipster
malloc is only there to allocate a block of memory. All you are really passing it is how many bytes to allocate, and all it gives you is a void* you are supposed to cast - in other words, it''s a "stupid" function (Zipster terminology ). On the other hand, new not only allocates the memory, but also constructs your object. You pass it the object you want to allocate, so it knows what to do. Moral of the story? Use new.

Topic Locked

This topic has been locked by a moderator. New replies are not allowed.

Sign in to reply to this topic.