malloc question
Author |
Message |
Thoerin
|
Posted: Tue Sep 02, 2008 4:47 pm Post subject: malloc question |
|
|
Could anyone explain why this program never seems to use more than ~90kB of memory (When checking with gnome-system-monitor, top, etc)? The pointer returned is not NULL when I pass a number less than the amount of free memory.
code: |
#include <stdio.h>
#include <stdlib.h>
int main(int argc, char *argv[]){
if(argc != 2)
{
printf("Usage: leak [Number of MB to allocate]\n");
return 1;
}
unsigned int megabytes;
sscanf(argv[1], "%u", &megabytes);
unsigned char *pointer = 0;
pointer = malloc(megabytes * 1000000 * sizeof(unsigned char));
printf("Allocation complete.\n");
printf("%X", pointer);
int tmp = getchar();
return 0;
}
|
|
|
|
|
|
|
Sponsor Sponsor
|
|
|
wtd
|
Posted: Tue Sep 02, 2008 4:56 pm Post subject: RE:malloc question |
|
|
Compiler optimization? Your compiler is realizing that you never actually use the memory allocated, so it doesn't bother to allocate any? |
|
|
|
|
|
Thoerin
|
Posted: Tue Sep 02, 2008 5:06 pm Post subject: Re: malloc question |
|
|
Hmmmm I tried compiling with -O0 before posting and it didnt help.
Just fixed it by setting to all zeros using memset, so I guess it was the optimizations after all.
Thanks for helping me out . |
|
|
|
|
|
btiffin
|
Posted: Wed Sep 03, 2008 2:22 am Post subject: RE:malloc question |
|
|
Kinda. malloc usually reserves pages. They won't physically load until needed. Complex stuff, but read http://en.wikipedia.org/wiki/Paging for a little background.
The vmstat utility may show you a better picture of what is going on.
When you really care to see what a compiler may be doing in terms of optimization, use a -S switch (for gcc that is) and take a boo at the assembler output. The .s files rarely lie or hide anything from you; plus it can be a real eye opener exercise. I'm occasionally amazed at how little assembler some complex operations can actually take. Or vice versa, how some C source becomes a nearly unmanageable morass of assembler code to trace through by hand.
Cheers |
|
|
|
|
|
wtd
|
Posted: Wed Sep 03, 2008 2:35 am Post subject: RE:malloc question |
|
|
Well yeah, when you're coding to god-awful complicated CPU architectures... |
|
|
|
|
|
|
|