[英]Analyze memory usage of a C program
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. 我知道有很多类似的问题(我不确定可能的重复)但我的问题是特定的。我在Windows和Unix运行C程序,我遇到分段错误(核心转储)错误.I知道那个错误的来源。这是因为我有时会通过分配一个大的整数数组来使用大量的内存。我的数组的大小每次都不同但我不能(大多数时候我不想)使用动态分配内存。
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? 我想要的是找到一种方法或工具来分析我的C程序的内存使用情况,以便设置对该数组的大小或我所做的任何其他大内存分配的限制。更具体的说让我们说该数组的大小介于4 *(2 ^ 4)字节和4 *(2 ^ 50)字节之间。最小值只有64个字节,但最大值是一个巨大的值。我怎样才能知道程序需要多少内存和什么是适当的限制? I define an array like this: 我定义了一个这样的数组:
int bigarray[rows][columns]
, int bigarray[rows][columns]
,
where rows is between 2^4 and 2^50 and columns is between 4 and 50. 行在2 ^ 4和2 ^ 50之间,列在4到50之间。
Get memory from the heap (malloc() and friends) instead of using the stack. 从堆(malloc()和朋友)获取内存而不是使用堆栈。 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. 您好,您可以使用工具valgrind
来检查内存消耗以及内存泄漏。
Below is link to Massif: a heap profiler
,hope it helps you. 下面是Massif: a heap profiler
链接Massif: a heap profiler
,希望它可以帮到你。
http://valgrind.org/docs/manual/ms-manual.html http://valgrind.org/docs/manual/ms-manual.html
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: 您将不得不使用新的/ malloc方法来充分利用它(当然比使用当前的堆栈方法更多),即如果您使用:
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 有了这个,在现代平台(Windows,Linux等)和32位程序上,你可以期待相当不错的尺寸为500 - 1000 MB
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.