• Announcements

    • khawk

      Download the Game Design and Indie Game Marketing Freebook   07/19/17

      GameDev.net and CRC Press have teamed up to bring a free ebook of content curated from top titles published by CRC Press. The freebook, Practices of Game Design & Indie Game Marketing, includes chapters from The Art of Game Design: A Book of Lenses, A Practical Guide to Indie Game Marketing, and An Architectural Approach to Level Design. The GameDev.net FreeBook is relevant to game designers, developers, and those interested in learning more about the challenges in game development. We know game development can be a tough discipline and business, so we picked several chapters from CRC Press titles that we thought would be of interest to you, the GameDev.net audience, in your journey to design, develop, and market your next game. The free ebook is available through CRC Press by clicking here. The Curated Books The Art of Game Design: A Book of Lenses, Second Edition, by Jesse Schell Presents 100+ sets of questions, or different lenses, for viewing a game’s design, encompassing diverse fields such as psychology, architecture, music, film, software engineering, theme park design, mathematics, anthropology, and more. Written by one of the world's top game designers, this book describes the deepest and most fundamental principles of game design, demonstrating how tactics used in board, card, and athletic games also work in video games. It provides practical instruction on creating world-class games that will be played again and again. View it here. A Practical Guide to Indie Game Marketing, by Joel Dreskin Marketing is an essential but too frequently overlooked or minimized component of the release plan for indie games. A Practical Guide to Indie Game Marketing provides you with the tools needed to build visibility and sell your indie games. With special focus on those developers with small budgets and limited staff and resources, this book is packed with tangible recommendations and techniques that you can put to use immediately. As a seasoned professional of the indie game arena, author Joel Dreskin gives you insight into practical, real-world experiences of marketing numerous successful games and also provides stories of the failures. View it here. An Architectural Approach to Level Design This is one of the first books to integrate architectural and spatial design theory with the field of level design. The book presents architectural techniques and theories for level designers to use in their own work. It connects architecture and level design in different ways that address the practical elements of how designers construct space and the experiential elements of how and why humans interact with this space. Throughout the text, readers learn skills for spatial layout, evoking emotion through gamespaces, and creating better levels through architectural theory. View it here. Learn more and download the ebook by clicking here. Did you know? GameDev.net and CRC Press also recently teamed up to bring GDNet+ Members up to a 20% discount on all CRC Press books. Learn more about this and other benefits here.
Sign in to follow this  
Followers 0
Misery

how to malloc memory properly?

22 posts in this topic

Hi,

I have a problem with malloc function.
I am using mallog in the manner:
[code]
TMyClass *ClInstancePtr;

CInstancePtr=(TMyClass*) malloc(sizeof(TMyClass)*NumOfElements);
[/code]
And it doesn't work properly. It behaves just lke I hadn't allocated anything.
F ex.:
[code]
ClInstance[2]=some values;
cout<<ClInstance<<endl;
output - some random data.
[/code]
What am I doing wrong?

Thanks in advance for any help.
Regards,
Misery.

PS.: When I use new[ ]/delete [ ] it works fine.
0

Share this post


Link to post
Share on other sites
Using [b]malloc[/b] doesn't construct any object in the array, it only allocates the requested memory.

Why do you need to use [b]malloc[/b] instead of [b]new[][/b]?
0

Share this post


Link to post
Share on other sites
[quote name='vdaras' timestamp='1309616091' post='4830346']
Why do you need to use [b]malloc[/b] instead of [b]new[][/b]?
[/quote]

Because I want to have possibility to resize my data without copying it.
How to make an array in place of malloc?
0

Share this post


Link to post
Share on other sites
You must copy the pointers but do not need to copy through objects referenced by them. New does not provide an equivalent to realloc unfortunately :-(
0

Share this post


Link to post
Share on other sites
[quote name='Misery' timestamp='1309618652' post='4830354']
[quote name='vdaras' timestamp='1309616091' post='4830346']
Why do you need to use [b]malloc[/b] instead of [b]new[][/b]?
[/quote]

Because I want to have possibility to resize my data without copying it.
How to make an array in place of malloc?
[/quote]

Use stl containers instead, it will save you a lot of bother. However, for the sake of explanation... you'll have to copy the data over anyway as malloc will allocate memory at a DIFFERENT address to the one you got when you first called malloc, thus you will lose the data. Not only that, but it will be leaked memory as you didn't free it before reallocating new memory. Anyway, use the new and delete operators as they are the "proper way of doing things", and for good reason. To allocate and delete arrays, you use new[] and delete[] operators respectively. If you wish to resize a dynamically created array, you would allocate a temporary dynamic array of existing size and then copy the contents of your existing array across. Then you would delete the contents of your existing array and reallocate a new array of the desired size, before transferring the contents of your temporary array across. Finally, delete you would the temporary array.
0

Share this post


Link to post
Share on other sites
[quote name='Misery' timestamp='1309618652' post='4830354']
[quote name='vdaras' timestamp='1309616091' post='4830346']
Why do you need to use [b]malloc[/b] instead of [b]new[][/b]?
[/quote]

Because I want to have possibility to resize my data without copying it.
How to make an array in place of malloc?
[/quote]

why not just use a vector or list ? (std::vector or std::list)

anyway as vdaras said malloc doesn't construct the object (the constructor is never called) it only allocates memory for it. (malloc is the C way of allocating memory, C doesn't support classes so trying to use a memory block allocator to create class instances will result in some major headaches)
0

Share this post


Link to post
Share on other sites
Why not stl?
Does something like [b]vector<bool>[/b] tell You guys something?:cool:
Thats why not stl.
-11

Share this post


Link to post
Share on other sites
[quote name='Misery' timestamp='1309620650' post='4830366']
Does something like [b]vector<bool>[/b] tell You guys something?:cool:

[/quote]

I'm not following. You can have containers of objects, no problem.
0

Share this post


Link to post
Share on other sites
[quote name='Misery' timestamp='1309620650' post='4830366']
Why not stl?
Does something like [b]vector<bool>[/b] tell You guys something?:cool:
Thats why not stl.
[/quote]


Don't use STL because it allows you to create a resizeable bool array?
0

Share this post


Link to post
Share on other sites
You're posting about problems stemming from errors caused by non-constructed non-pod types (a very dangerous thing to do), but are going to criticize the standard library for having strange resizable-bool-array iterator semantics?

Are you making a resizable array of bools or a resizable array of non-pod types?
0

Share this post


Link to post
Share on other sites
[quote name='King Joffrey' timestamp='1309621370' post='4830369']
[quote name='Misery' timestamp='1309620650' post='4830366']
Does something like [b]vector<bool>[/b] tell You guys something?:cool:

[/quote]

I'm not following. You can have containers of objects, no problem.
[/quote]


Blind guess: He's probably referring to the overhead. Well, you also have the same with an array of bools. If you want to use only a single bit for each bool you need to use bitmasks on top of that. Still until now, there wasn't a single reason not to consider STL containers.

0

Share this post


Link to post
Share on other sites
I need resizable bool array with tightly packed data. i mean one bit = one bool value.
Second thing is that I will use millions of instances of this class. And vector<bool>
requires (with zero entries) 20 bytes of memory. At start. Thats too much.
Therefore I have decided to create a class that has ability to resize, contains chars, and has ability to access every bit in char.
The only last problem is how to resize this fast.

Why did You guys vote down?
0

Share this post


Link to post
Share on other sites
[quote name='Misery' timestamp='1309618652' post='4830354']
[quote name='vdaras' timestamp='1309616091' post='4830346']
Why do you need to use [b]malloc[/b] instead of [b]new[][/b]?
[/quote]

Because I want to have possibility to resize my data without copying it.
How to make an array in place of malloc?
[/quote]Then the problem is that you need to stop wanting to do that. Get out of this mindset that copying is slow - It isn't. Heck [url="http://lwn.net/Articles/255364/"]here[/url]'s a good read on how they modified a matrix multiply routine to copy the matrix internally leading to a more than four times speedup.


You should never use realloc under any circumstances in a C++ program. In fact you shouldn't even use it in a C program as I don't think I've ever seen anyone posting using it both correctly and appropriately. Besides, realloc isn't always going to avoid copying either.
0

Share this post


Link to post
Share on other sites
[quote name='iMalc' timestamp='1309639192' post='4830459']
You should never use realloc under any circumstances in a C++ program. In fact you shouldn't even use it in a C program as I don't think I've ever seen anyone posting using it both correctly and appropriately. Besides, realloc isn't always going to avoid copying either.
[/quote]
Well, although Misery was beginner, this is not beginners forum...

I have used realloc extensively in both C and C++ programs and have not had any problems. Right tool for the right job :wink:


0

Share this post


Link to post
Share on other sites
[quote name='Brother Bob' timestamp='1309629739' post='4830410']
Assuming two pointers and an integer, that adds up to 20 bytes (assuming a 64 bit system with 64 bit pointers and 32 bit integers).
[/quote]
To be fair, MSVC 2010 has a 20 byte std::vector<bool> even in 32 bit release builds. Its std::vector<bool> is implement in terms of std::vector<unsigned int>; it's the size of std::vector<unsigned int> plus its own data.
0

Share this post


Link to post
Share on other sites
[quote name='Lauris Kaplinski' timestamp='1309640193' post='4830463']
I have used realloc extensively in both C and C++ programs and have not had any problems. Right tool for the right job :wink:
[/quote]

How to do it properly? I will use memory pools anyway, but I need to finish that class I have begun.

And I'm not really a beginner, however I am not educated programmer, but fluid mechanics engineer, so many things for me are unclear.
I'm just an user of programming.

Thanks for any help.
0

Share this post


Link to post
Share on other sites
[quote name='Hodgman' timestamp='1309621495' post='4830371']
You're posting about problems stemming from errors caused by non-constructed non-pod types (a very dangerous thing to do), but are going to criticize the standard library for having strange resizable-bool-array iterator semantics?

Are you making a resizable array of bools or a resizable array of non-pod types?
[/quote]

vector <bool> has not only strange non-stl semantics. It also forces compiler to optimise code inproperly. If many clever ppl say: never use vector<bool> i do not use it.
And the other thing is that vectors are quite big 20 bytes for an empty vector. One more thing is that vectors reserve much more memory than needed. I know that one can use v.reserve()
but after I exceed reserved memory it will reserve again twice more than needed and so on.
In fact I need a bit array. My basic class is byte that allows me to access every bit.
-1

Share this post


Link to post
Share on other sites
[quote name='Lauris Kaplinski' timestamp='1309640193' post='4830463']
[quote name='iMalc' timestamp='1309639192' post='4830459']
You should never use realloc under any circumstances in a C++ program. In fact you shouldn't even use it in a C program as I don't think I've ever seen anyone posting using it both correctly and appropriately. Besides, realloc isn't always going to avoid copying either.
[/quote]
Well, although Misery was beginner, this is not beginners forum...

I have used realloc extensively in both C and C++ programs and have not had any problems. Right tool for the right job :wink:
[/quote]Then you [i]appear[/i] to be an exception to the rule.

Of course using realloc etc was at best unnecessary, and at worst you just haven't seen the issues yet and they'll still get you one day.
0

Share this post


Link to post
Share on other sites
[quote name='Misery' timestamp='1309689528' post='4830574']
[quote name='Lauris Kaplinski' timestamp='1309640193' post='4830463']
I have used realloc extensively in both C and C++ programs and have not had any problems. Right tool for the right job :wink:
[/quote]

How to do it properly? I will use memory pools anyway, but I need to finish that class I have begun.

And I'm not really a beginner, however I am not educated programmer, but fluid mechanics engineer, so many things for me are unclear.
I'm just an user of programming.
[/quote]
[code]MyType *newptr = (MyType *) realloc (oldptr, newsize * sizeof (MyType));
for (size_t i = oldsize; i < newsize; i++) {
// Initialize your new data here
}[/code]
[list][*]Do not try it with non-POD types! Although there is placement new, things get ugly fast.[*]Do not forget, that the block address may change - thus you should NOT keep extra pointers to it.[*]Do not forget, that your old memory block may be freed and completely new one allocated. Thus you cannot keep pointers to individual objects.[*]Your old objects (datablocks) will be copied bit-by-bit. If this is not the intended behaviour, do not use it.[*]Your new objects (datablocks) will be uninitialized - i.e. filled with arbitrary garbage.[*]If new memory block is allocated, neither destructors nor copy contructors are called[*]It is better to avoid MyType constructors altogether. Then you cannot expect it to be called (it won't).[/list]
In general, there should be very good reasons to use malloc/realloc/free in C++ code. One possible cause is to reduce unnecessary pointer dereferencing - something like:

[code]struct VectorPath {
unsigned int size;
unsigned int nelements;
Rect bbox;
float coordinates[2];
};[/code]

In this example you can construct paths of arbitrary length by allocating more memory than the size of given struct and then access coordinates >= 2. I think this may be violating C/C++ standard, but I do not think there is or will be any compiler that does not support it. But in any case such constructs require good and clean encapsulation - or they'll bite you.

My suggestion is - use new/delete and copy manually, or use vectors. Encapsulate the required behaviour into clean API and get your program working. Then you can experiment with more esoteric things ;-)
0

Share this post


Link to post
Share on other sites
[quote name='Misery' timestamp='1309689870' post='4830576']
[quote name='Hodgman' timestamp='1309621495' post='4830371']
You're posting about problems stemming from errors caused by non-constructed non-pod types (a very dangerous thing to do), but are going to criticize the standard library for having strange resizable-bool-array iterator semantics?

Are you making a resizable array of bools or a resizable array of non-pod types?
[/quote]

vector <bool> has not only strange non-stl semantics. It also forces compiler to optimise code inproperly. If many clever ppl say: never use vector<bool> i do not use it.
And the other thing is that vectors are quite big 20 bytes for an empty vector. One more thing is that vectors reserve much more memory than needed. I know that one can use v.reserve()
but after I exceed reserved memory it will reserve again twice more than needed and so on.
In fact I need a bit array. My basic class is byte that allows me to access every bit.
[/quote]


Why not override the allocator?
0

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!


Register a new account

Sign in

Already have an account? Sign in here.


Sign In Now
Sign in to follow this  
Followers 0