0

I am unable to allocate memory using the following code:

int *h_VC = (int *)malloc(sizeof(int)*SIZE); //SIZE is 19200
if(h_VC==NULL)
{
 printf("Memory Not avaialble");
}

My code uses the above block in a while loop and is run several times. I have 8GB memory. I am monitoring the free memory at the same time when running the code.
The memory allocation is failing although i have arround 3GB of free memory left.
What could be the problem?

scatman
  • 14,109
  • 22
  • 70
  • 93
  • I assume you're using a 64 bit OS? – Seth Carnegie Dec 13 '11 at 13:02
  • 2
    Just a note: don't cast the returned pointer of `malloc`. Theres no need to and it is possibly dangerous. – Constantinius Dec 13 '11 at 13:03
  • Don't know if this is the case, but it might help: http://stackoverflow.com/questions/605845/do-i-cast-the-result-of-malloc – supertopi Dec 13 '11 at 13:04
  • I test it,and it works fairly – Moein Hosseini Dec 13 '11 at 13:09
  • can you offer more details? OS, compiler, etc? – INS Dec 13 '11 at 13:10
  • 3
    If it's a 32-bit program running in a 64-bit OS, you can still have plenty of free memory in the OS, but exhausted address space in the program due to memory fragmentation or leaks or just too many too big allocations. Which one it is it's hard to tell without any additional information about the program and OS. – Alexey Frunze Dec 13 '11 at 13:31
  • Perhaps you're running into `ulimit -v`? – Daniel Fischer Dec 13 '11 at 13:32
  • @arncore: First, you don't have to cast a `void*` to a specific pointer type. This happens automatically and does not invoke any compiler warnings as it is mandated by the standard. It might be dangerous because you might link to another function with the name `malloc` but another return type and would not even notice, since you are explicitly casting. This would also not invoke any warnings since the compiler would assume you know what you are doing. Avoid explicit casts, unless necessary is a good rule of thumb. – Constantinius Dec 13 '11 at 14:02
  • @Alex: agreed. If it's 32 bit, and really 5GB allocated, then the OS deals with a "-1GB" linear address space situation, and must be swapping like crazy to handle. – gnometorule Dec 13 '11 at 14:13

2 Answers2

5

Anything could be the problem. Replace the printf with

perror("");

to get a hint.

Fred Foo
  • 355,277
  • 75
  • 744
  • 836
0

I am using Visual Studio as a compiler. Compiling the program as x64 solved the issue.
thanks to Alex's comment.

scatman
  • 14,109
  • 22
  • 70
  • 93