无论代码长度如何,以下代码的内存要求有何不同?

How the memory requirements of the following codes are different irrespective of the code-length?

本文关键字:代码 内存 何不同      更新时间:2023-10-16
// An efficient program to randomly select a number from stream of numbers.
#include <iostream>
using namespace std;
#include <stdlib.h>
#include <time.h>
/* A program to randomly select a item from stream[0], stream[1], ..
stream[i-1]*/

int main()
{
int stream[] = { 1, 2, 3, 4 };
int n = sizeof(stream) / sizeof(stream[0]);
// Use a different seed value for every run.
srand(time(0));
cout << "Random no. selected: " << stream[(rand() % n)] << "n";
return 0;
}

上面的C++代码需要从 2.9 到的内存...(某物(MB 或更大,达到 3.04。(某物(MB 或更大。

并考虑以下 C 代码:

/* An efficient program to randomly select a number from
stream of numbers.*/
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
/* A function to randomly select a item from stream[0], stream[1], .. 
stream[i - 1]*/
int selectRandom(int x)
{
static int res;    // The resultant random number
static int count = 0;  //Count of numbers visited so far in stream
count++;  // increment count of numbers seen so far
// If this is the first element from stream, return it
if (count == 1)
res = x;
else
{
// Generate a random number from 0 to count - 1
int i = rand() % count;
// Replace the prev random number with new number with 1/count 
//probability
if (i == count - 1)
res = x;
}
return res;
}
// Driver program to test above function.
int main()
{
int stream[] = { 1, 2, 3, 4 };
int n = sizeof(stream) / sizeof(stream[0]);
// Use a different seed value for every run.
srand(time(NULL));
for (int i = 0; i < n; ++i)
printf("Random number from first %d numbers is %d n",
i + 1, selectRandom(stream[i]));
return 0;
}

上面的代码,需要 1.28 范围内的内存。(某物(MB 或更大,但肯定小于 2MB。

我的问题是,为什么第一个程序比第二个程序占用更多的空间,以及如何?

使用您提供的在线编辑器,内存使用情况似乎与实际分配不符。如果我用malloc(1);编写一个程序,"内存"统计信息与执行malloc(10000000);相同。我被引导相信这个统计数据只是可执行文件的大小。