-
Allocating memory in C++
I need to allocate a 64000 byte array to use as a virtual screen. I tried using "new char[64000]" but that returns a null pointer every time. How do i allocate that much memory in C++? (Im trying to stay away from C code because id have to include extra header files.)
-
Code:
void* p = malloc(64000);
Using "new" includes the malloc.h header anyway.
Z.
-
malloc returns a void pointer (like Zaei showed).
For chars try:
char *p;
p = (char *) malloc(64000);
Sine they are chars
p = (char *) calloc(64000);
This inits memory to all zero (null terminators) as well as allocating it. That way, various kinds of string operation will not choke.
-
uses a lot of heap memory. If you want virtual memory:
Code:
BYTE* pByte = (PBYTE) VirtualAlloc(NULL, 65000, MEM_RESERVE | MEM_COMMIT, PAGE_READWRITE);
but for 65 k, this could be overkill, it is rather for memory amounts starting with 100k :)
-
There's also the LocalAlloc function.
-
LocalAlloc and GlobalAlloc are deprecated.
Anyway, new doesn't return NULL - it throws an exception. I just tried, and I could allocate more than 64K...are you using a 16-bit, non-standard compiler by any chance?
-
Yup, im using turbo c++ 3.0. Right now though im downloading watcom c/c++, hope its better.
-
Ah...if it's 16-bit I don't think you can allocate an array larger than one segment...although 64000 is less than 65535 :confused:
Watcom came with a 32-bit DOS extender so you should be fine :)
-
I dont know if it will work, but you may try "byte huge scr[64000]". I found this in some 16-bit code I have laying around on the HDD. It is C code, but you might as well try it =).
Z.
-
Hi ChimpFace9000, if you always want to have 64000 chars, why not, instead of allocating memory, declare
char XX[64000];
Ok back to the point, I don't see why it always return null pointer.
Is it bcos of 16 bit compiler(TC 3.0)? The total data memory used by the program is more than 65535?
Let's hope watcom C++ solve your problem.;)
-
Ok i downloaded Watcom c++, and it sucks.
Are there any other modern dos C++ compilers? Dont say DJGPP, i hate that compiler. An exe from it is like 200 kb! Thats un-acceptable.
-
In DOS, you should be able to just take the memory, without allocating it. Just assign the memory location to a pointer, and use it. Sure, you might screw up some other program, but big deal (it's DOS =) =).
Z.
-
maybe you should check the compile options of DJGPP. Jump'n'Bump was compiled with DJGPP and it is only 67k.
-
I think the linker will accept COFF .obj files, so if that's what the assembler produced. You'd also need a header file for them (set up with whatever calling convention your assembler procs use).