次のプログラムを使用して、malloc
を使用して1GBのメモリを動的に割り当てました。mallocはRAMの使用に影響しません。なぜですか?
#include <malloc.h>
#include <stdio.h>
int main()
{
int i;
char **ptr = malloc(10000 * sizeof(char*));
// Dynamically allocate 1GB of space
for (i=0; i<10000; i++) {
ptr[i] = malloc(1024 * 100 * sizeof(char));
ptr[i] = "How do you do?";
ptr[6888] = "How are you?";
}
// Print string at some random locations
printf("%s\n", ptr[3688]);
printf("%s\n", ptr[6888]);
printf("%s\n", ptr[6889]);
getchar();
return 0;
}
出力:プログラムの実行前に
[email protected]:~$ ./a.out
How do you do?
How are you?
How do you do?
RAM使用量:プログラムの実行中に
[email protected]:~$ free -h
total used free shared buffers cached
Mem: 2.9G 2.0G 981M 16M 28M 569M
-/+ buffers/cache: 1.4G 1.5G
Swap: 0B 0B 0B
RAM使用量:
[email protected]:~$ free -h
total used free shared buffers cached
Mem: 2.9G 2.0G 945M 16M 28M 569M
-/+ buffers/cache: 1.4G 1.5G
Swap:
0B 0B 0B
出力は、罰金のようです。しかし、私はRAMの使用量がプログラムの実行中に1GB高くなるはずです。しかし、それはかなり正常なようです。私はOSがメモリ上でガベージコレクションをしたとは思わない。私が割り当てたメモリをOSが解放すると、出力が得られず、実行時にセグメンテーションフォルトが発生する可能性があります。
注:私はubuntuを使用しています。
a)C++またはC? b)strcpyが何であるかを学ぶ。 c)自由が何であるかを学ぶ。 d)あなたはほとんどのメモリに書き込んでいません。 「どうやってやるの?」はどこにも書かれていない。 – deviantfan
これはC++ではありません。 – Olaf
@ deviantfan、そうです、私はstrcpyを使うべきです。 – Jobin