Allocating memory in a book called Expert C programming

The exercise asks me to see what happens if the memory block to be allocated is less than 1 MB in the following program:

#include <stdio.h>
#include <stdlib.h>
main()
{
    int MB=0;
    while(malloc(1<<20))
        ++MB;
    printf("Allocated %d MB total\n",MB);
}

Result on my laptop

Allocated 3056 MB in total

How do I change the program as follows:

#include <stdio.h>
#include <stdlib.h>
main()
{
    int MB=0;
    while(malloc(1<<19))
        ++MB;
    printf("Allocated %d MB total\n",MB/2+MB%2);
}

And the result

Allocated 3045 MB in total

Did I change my program correctly? And why is the result less than 3056 MB?

+4
source share
2 answers
  • Yes, your program is fine. (Although always rounding up the number of megabytes up is a bit unconventional.)

  • free, , , . , , . , - . , , , . , size_t , , , .

malloc ( 4K). - , size_t. , , 1% , 1% .

, malloc . 1 , 3056 . 4 , , 3056 * 4k 12 . ( , 12 mebibytes, , mebi.) , 3068 .

½ , 3045 * 2 - 1 ( , ). 6089 , 23,8 3044,5 , 3068,3 .

, malloc , , , .

+4

1. . 1MB , , .

2. .

3. , , progrm. (RTOS), , .

+4

Source: https://habr.com/ru/post/1543330/


All Articles