Memory request

0

I tell you my question. I have a simple program in C, I am working with linux Mint. The only thing he does is ask for memory until he can not ask for more. Here I put the code:

#include <stdio.h>
#include <stdlib.h>

int main(){


    printf("Iniciando creacion de matrices...\n");      

    double *p;
    int i=1;
    int cuenta=0;
    long int total;
    //printf("%lu",sizeof(double));
    while(i){
        p=malloc(10000*40000*sizeof(double));
        cuenta++;
        if(p==NULL){
            printf("ERROR %d \n",cuenta);
            break;
        }else{
            printf("CORRECTO %d \n",cuenta);
        }
    }
    total=(long int)10000*40000*cuenta;
    printf("%ld\n",total);
    printf("Listo\n");

    return 0;
}

I execute it again and again. According to my interpretation, since the memory is never released, it will be occupied and the next execution could not be made the memory allocation because I would have already assigned the memory in the previous execution and it would still be occupied. But this is not the case, I can execute it and execute it, and the value of the variable account is always the same: that is, it always makes around 43,980 assignments.

Well this code is just a test of a doubt that came to me when doing large memory allocations. But my curiosity can basically be found in the code.

Thanks for your help.

    
asked by Patricio 10.09.2017 в 23:36
source

1 answer

0

In this section:

while(i) {
    p = malloc(10000 * 40000 * sizeof(double));
    cuenta++;

    if (p == NULL) {
        printf("ERROR %d \n",cuenta);
        break;
    } else
        printf("CORRECTO %d \n",cuenta);
}

What you are basically doing is assigning to variable p the memory address you are saving with malloc , then in the first iteration to p you assign the address of a block of memory (which you reserve with malloc ), in the second iteration to p you assign the address of another block of memory (that you reserve with malloc ) and so on until p of NULL , which considering the code that You will only occur when there is no more memory that you can reserve, but this does not necessarily have to happen in the second iteration.

Example

As if I did not understand well, imagine that your memory is like a chess table and in each iteration of your while you are saving a cell with malloc and the address of that cell is assigned to p , in the second iteration you re-book another cell (you can not reserve the same cell, since it was already reserved and you did not release it, then malloc assigns you another cell of the board) and you reassign the address of that cell at p , this will continue until there are no more available cells that you can reserve.

    
answered by 11.09.2017 в 01:19