memory-user.c

closed account (Nwb4iNh0)
Can someone write comments on this code to be more understandable

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
  

#include <stdio.h>
#include <stdlib.h>
#define NITER 10000
int main(int argc, char *argv[]) {
if (argc != 2) {
fprintf(stderr, "usage: memory-user <memory>\n");
exit(EXIT_FAILURE);
}
int memory = atoi(argv[1]) * 1024 * 1024;
int length = (int)(memory / sizeof(int));
int *arr = malloc(memory);
if (arr == NULL) {
fprintf(stderr, "malloc failed\n");
}
for (int i = 0; i < NITER; i++) {
for (int j = 0; j < length; j++) arr[j] += 1;
}
}
free(arr);
return 0;
Last edited on
The code appears to just be copied from somewhere, so as far as we can tell, you have shown zero effort in tackling this assignment.

Tell us specifically where you start to not understand the code, and we can help you bit by bit instead of just writing the comments for you. Give us a guess at what you think a line you don't understand is doing. If it's a certain keyword or function you don't understand, try searching it online.

Seems to be modified from https://github.com/xxyzz/ostep-hw/blob/master/13/memory-user.c
Last edited on
that code does not do anything.
I mean it pokes values into the piratey arr variable and then throws the values away, zero sum game of nothing accomplished. It looks like a quick example of how to use malloc, at a guess? Its a little hard to read with the braces not aligned and the bad variable names and such.
Last edited on
"Properly" formatted reveals this code snippet is a huge steaming pile of manure that shouldn't compile:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
#include <stdio.h>
#include <stdlib.h>
#define NITER 10000
int main(int argc, char* argv[])
{
   if (argc != 2)
   {
      fprintf(stderr, "usage: memory-user <memory>\n");
      exit(EXIT_FAILURE);
   }
   int memory = atoi(argv[1]) * 1024 * 1024;
   int length = (int)(memory / sizeof(int));
   int* arr = malloc(memory);
   if (arr == NULL)
   {
      fprintf(stderr, "malloc failed\n");
   }
   for (int i = 0; i < NITER; i++)
   {
      for (int j = 0; j < length; j++) arr[j] += 1;
   }
}
free(arr);
return 0;
It can do something that surprises us; the program may engender undefined behaviour.

malloc allocates uninitialized storage; the program tries to increment uninitialized scalars.

(atoi may cause undefined behaviour if the converted integer value is outside of range,
strtol is a safer alternative)
Topic archived. No new replies allowed.