James Parsons
James Parsons

Reputation: 6057

calloc created array is not acting as expected

I was bored and wanted to make a program to crash my computer :P. I would have it uselessly and redundantly allocate memory until the crash. The code I created so far is here:

#include <cstdlib>
#include <cstdio>

int main(int argc, const char *argv)
{
    int n = 0;
    while (1)
    {
        n++;
        int* buffer = (int*)malloc(n ^ n);
        int* buffer_buffer = (int*)calloc(n, sizeof(buffer));
        for (int i = 0; i < n; i++) {
            printf("%p", &buffer);
            printf("\n");
            buffer_buffer[i] = (int)buffer;
        }
    }
}

The code works(it crashes the computer), but does not work as expected.I wanted to go more into the process of the how it worked and what exactly it was doing, so I set a few breakpoints and decided to step through it. I expected to see the buffer_buffer reallocated again and again containing n numbers of buffer, but it does not. Instead, my debugger shows that buffer_buffer contains a single value that sometimes will change, and a single value(the integer cast of buffer at least I hope) is logged every go round the loop. I was expecting the buffer_buffer to grow with n number of elements every time around the for loop comes around, but it only has one element. To visualize this, here is a screenshot of the debugger:

Debugger

Again I am somewhat tired and this is probably an issue with my loop logic. Does anyone know why my program is experiencing this unexpected behavior? I am using the Microsoft Visual Studio debugger

Upvotes: 1

Views: 343

Answers (1)

rici
rici

Reputation: 241861

Probably your debugger doesn't know how big buffer_buffer is, since that variable is simply declared as being a pointer to an int. (That's not correctly typed; buffer_buffer is used to hold values of buffer which is an int*, so buffer_buffer must be an array of int*, which means that you should declare it as int**, i.e. a pointer to a sequence of int*.) One of the little challenges in debugging C programs is that the length of an array is not stored anywhere at all; you have to keep track of it yourself. So the debugger doesn't know either.

Also, n^n is 0, since ^ is the XOR operator. I don't know if that is what you intended.


(Actually, it's not quite true that the allocation size isn't stored anywhere. It might be, or some approximation to it might be. But it's stored in the internals of the memory allocation library, and there is no way to get at it. And anyway, it might not be correct, because the library sometimes allocates more than you asked for, and it only remembers what it allocated, not what you asked for.)

Upvotes: 4

Related Questions