Is this syntax ok?

P

pertheli

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;
 
R

Rolf Magnus

pertheli said:
Hello all

What is the difference between Method 1 and Method 2 below?

If sizeof(short) == 2 * sizeof(unsigned char), there is none.
Is Method 2 safe to use?

Well, I don't know what you mean by 'large', but allocating large blocks
of memory might fail depending on the system. It should however not
crash in any case, but rather return a null pointer on failure.
 
P

Peter Koch Larsen

pertheli said:
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
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,770
Messages
2,569,584
Members
45,075
Latest member
MakersCBDBloodSupport

Latest Threads

Top