Allocation bursts memory into recursive function in C [closed]

1

I created a program that is allocating 4 bytes of memory successively through a recursive function:

#include <stdio.h>
#include <stdlib.h>
#define BUF 2

void overflow(int payload){
    payload = payload - 1;
    int stack = (int)malloc(payload * sizeof(int));
    payload = payload + 1;
    overflow(payload);
}


int main(void){
    overflow(BUF);
    return 0;
}

It turns out that it stops working before it can consume all memory, would it be some kind of control of Windows itself to ensure system integrity, or is it a programming error?

How could I circumvent this and leave the program consuming memory to the top and when do I get to the top stop allocating memory?

I'm using windows 7 64 bit

    
asked by anonymous 12.09.2017 / 21:14

2 answers

2

It is a programming error and stack overflow because the recursion has no end. If you moved to a loop and it worked, it is because the loop has a condition that closes it, otherwise there would be no end, although there would be no stack overflow. But at some distant moment it would burst the heap as well.

#include <stdio.h>
#include <stdlib.h>
#define BUF 2

void *overflow(int payload) {
    if (--payload) {
        int *stack = malloc(payload * sizeof(int));
        overflow(payload);
    }
}

int main(void) {
    overflow(BUF);
}

See running on ideone . And no Coding Ground . Also I put it in GitHub for future reference .

    
13.09.2017 / 05:54
0

Try the following code, taken from a response in StackOverflow in English :

main() {
  int Mb = 0;
  while ( malloc(1<<20)) ++Mb;
  printf("Allocated %d Mb total\n", Mb);
}

(Declare stdio and stdlib for this example)

    
12.09.2017 / 22:47