简体   繁体   中英

Didn't allocate memory by using malloc

I am facing a problem on malloc for allocating memory:

ByteArr = (BYTE *)malloc(sizeof(SHORT) * 20); 

I m getting error like

"CXX0030: Error: expression cannot be evaluated"

But if i am taking 428 or 1024 instead of 20 than its allocating the memory.Can you please tell me where is the problem ...thanks.

Extending lavino's answer and the fact this problem does not happen when you use the values like 1024 indicates to me that you are trying to read/write from a memory which is outside what you have allocated. Looks like you have allocated 20 shorts and try to read 100th short usinf the ByteArr pointer. This will show the 'expression can not be evaluated' error in the debugger.

I'm not sure why it's working for other values, but the expression that it can't evaluate might be the missing variable for the ByteArr. You have the type specified, but no variable to assign.

BYTE *myByteArr = (BYTE *)malloc(sizeof(SHORT) * 20);

Updated:

That's a message in the debugger, telling you that the memory pointed to by the return isn't a valid memory block.

[Not this] Is the return value ENOMEM ? If so, for some reason memory isn't being allocated, or the target variable isn't compatible with the return value of the malloc() call.

[Not this] What is the type of ByteArr ? It's BYTE* , right? And not BYTE[] ?

[How about this?] At the time of the debugger message, is ByteArr still pointing to the same address that was returned by the malloc() call? You might be off the end of the array, or completely outside the allocated memory block.

I guess the problem is that it should be:

Byte* ByteArr = (BYTE *)malloc(sizeof(SHORT) * 20);

instead of:

Byte ByteArr = (BYTE *)malloc(sizeof(SHORT) * 20);

Now, I am not sure what is ByteArr in your code but from one of your comments to another answer I have sort of picked out that this is the problem.

Reference this page:

http://www.codeguru.com/forum/showthread.php?t=430940

It seems you need allocate more space. Also google is always a good helper.

What I feel is there might be one more allocation, before this allocation, and there you are over running the allocated memory space. And then again trying to allocate here, where malloc logic may be failing.

malloc is not finding next free block because of previous case of over running and hence not able to allocate for mentioned space, and if you give 1024 malloc is finding one block where that much free space is available and is getting allocated.

Try to fix that allocation then this problem will be solved.

I think you are correcting your memory somewhere else in your software. Try using a tool like Rational PurifyPlus from IBM, or Bounds Checker .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM