I know there are a lot of similar questions(i am not sure for a possible duplicate) but my question is specific enough.I am running a C program in Windows and Unix and i am experiencing a segmentation fault(core dumped) error.I know the source of that error.It's because i sometimes use a huge amount of memory by allocating a big array of integers.The size of my array is different every time but i can't(mostly i don't want to) use dynamic allocation of memory.
What i want is to find a way or a tool to analyze the memory usage of my C program in order to set a limit to the size of that array or in any other big memory allocation i make.To be more specific let's say that the size of that array is between 4*(2^4) bytes and 4*(2^50) bytes.The minimum is only 64 bytes but the maximum is an enormous value.How can i find out how much memory my program needs and what is a proper limit to set? I define an array like this:
int bigarray[rows][columns]
,
where rows is between 2^4 and 2^50 and columns is between 4 and 50.
Get memory from the heap (malloc() and friends) instead of using the stack. The heap permits much larger allocations.
int *bigarray = malloc(sizeof(int)*rows*columns);
/* to access row r, column c */
bigarray[r*columns+c] = 42;
/* equivalent method to access row r, column c */
*(bigarray+r*columns+c) = 42;
Hi you can use tool valgrind
to check for memory consumption as well as memory leaks.
Below is link to Massif: a heap profiler
,hope it helps you.
To calculate the (theoretical) memory consumption:
printf("%d MB", (rows*columns*sizeof(int))/1024/1024);
.
You will have to use a new/malloc approach to get the most from it (definitely more than with your current approach on stack), ie if you use:
int *bigarray= new int[columns*rows];
and then access it as
val= bigarray[ x*columns + y]; // instead of bigarray[x][y];
With that, on modern platforms (Windows, Linux, etc.) and 32bit program you could expect to be reasonably ok with sizes of 500 - 1000 MB
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.