【发布时间】:2014-05-18 05:24:20
【问题描述】:
假设我有以下程序 - 从命令行获取一个数字(例如 10M),创建一个这个大小的数组,用随机整数填充它,等待 15 秒然后退出。它应该占用多少内存? (给定10M的输入)
#include <stdio.h>
#include <string.h>
#include <time.h>
#include <stdlib.h>
#include <unistd.h>
int main(int argc, char **argv)
{
printf("running\n");
long long size = atoi(argv[1]);
printf("%lld\n", size);
int *myArray = malloc(size * sizeof *myArray);
printf("allocated array\n");
srand(time(NULL));
for (long long i=0;i<size;i++) {
if (i == 0) {
printf("first iteration\n");
}
int r = rand();
myArray[i] = r;
}
printf("Allocated\n");
sleep(15);
printf("Done\n");
}
给定输入
./a.out 10000000
这(在 Mac 活动监视器中)占用 38.4M。
我的问题是:有没有办法在给定这些参数的情况下预测一个简单的 C 应用程序的 RAM 使用情况? 即一个 10M 整数的数组。
【问题讨论】:
-
我认为这个等式应该显示大约 99% 的内存(以字节为单位)。
size * sizeof *myArray -
P.S.> 在 myArray 初始化之前你怎么能做到
sizeof *myArray?没有意义。 -
你要找的是
malloc(size * sizeof(int)); -
@SSpoke
sizeof的这种使用是合法且推荐的:stackoverflow.com/q/373252/509868 -
@anatolyg 我猜它可以工作,因为 malloc asm 是在 myArray 之后执行的?还是不好看。