memory allocation different when lookup in system monitor

I write a c program to allocate specific size of memory and free them in Ubuntu.

Defaultly, it create 100MB memory by malloc 1MB for each entry of a 100 size array.
When I lookup system monitor and find the program, it only shows 292KiB in the memory field.
Is that true?


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
#include <stdlib.h>
#include <stdio.h>
#include <sys/ioctl.h>
#include <fcntl.h>
#include <unistd.h>
#include <string.h>
#include <sys/param.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <stdint.h>
#include <getopt.h>

static const char *progname;
struct optargs {
 int size;
};

static struct option long_options[] = {
 {"size",                1, 0, 's'},
 {"help",                0, 0, 'h'},
 { NULL,                 0, 0,  0 }
};

void Usage() {
 printf("Allocate 150MB memory\n./program --size|-s 150\n");
 exit(0);
}

int run(struct optargs opts) {
 char *ptr[opts.size];
 int steps = 4;
 int sz_unit = 1048576;

 for (int i=0;i<opts.size;i++) {
  ptr[i] = (char*)calloc(sz_unit, sizeof(char));

system("read -p 'Press Enter to continue...' var"); // lookup the system monitor when pause
 for (int i=0;i<opts.size;i++) {
  free(ptr[i]);
 }

 return 0;
}

int main(int argc, char **argv) {

 int opt_size = 0;
 int c;
 struct optargs opts;
 progname = argv[0];

 while ((c = getopt_long(argc, argv, "s:h", long_options, NULL)) != -1) {
  switch(c) {
   case 's':
    opt_size = 1;
    opts.size = atoi(optarg);
    break;

   default:
    Usage();
    break;
  }
 }

 if (!opt_size)
  opts.size = 100;
 printf("Will allocate %dMB memory\n", opts.size);
 run(opts);
 return 0;
}
Last edited on
https://duckduckgo.com/?q=linux+overcommit+memory&atb=v203-1&ia=web
Linux waits until you actually start doing things like
ptr[i][0] = 1;
before actually mapping memory into your program address space.

Topic archived. No new replies allowed.