"pertheli" <pe******@hotmail.com> skrev i en meddelelse
news:48**************************@posting.google.c om...
Hello all
What is the difference between Method 1 and Method 2 below? Is Method 2
safe to use?
typedef short Word;
typedef unsigned char Char;
int nAllocSize = large number;
//Method 1 crashes in my machine for large nAllocSize
Word* pShort = (Word*)malloc(nAllocSize*sizeof(Word));
//Method 2 seems ok even if nAllocSize is large
Word* pShort;
Char* pChar = (Char*)malloc(nAllocSize*sizeof(Char)*2);
pShort = (Word*)pChar;
Do not use malloc. Use new instead:
Word* pShort = new Word[nAllocSize];
// pShort will point to the allocated area or an exception will be
thrown
If you dont want exceptions here, use:
Word* pShort = new(std::nothrow) Word[nAllocSize];
// If allocation fails, pShort will be 0
Without knowing your program i still believe that using the standard library
would be even better:
std::vector<Word> word_vector(nAllocSize);
You will have to live with the possible exception here, but all dynamic
memory management has been taken care of by the system.
Apart from this, it seems that you try to make an abstraction of "short" by
introducing your typedef. Why then do you name the variable pShort? If
anything it should be pWord, although i detest variable names that aim at
describing the underlying type. After all, C++ is a strongly typed language.
Kind regards
Peter