0

I imagine this is a pretty simple question, but I'm curious what's going on.

I'm toying around with a C program which dynamically allocates a large amount of memory. While running it, I'm keeping tabs on how much memory task manager currently says is in use. I noticed that rather than abruptly hiking up, the memory usage seems to instead slowly steadily increase as the program runs. My impression was that malloc() allocates memory right as it's called, so the incremental increase in memory is confusing to me. Is this to be expected, or is there something specific about my code that's causing it to happen?

Here's the script of my code:

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

int main(void){
    int d1 = 1000;
    int d2 = 540;
    int d3 = 8;

    printf("Allocating memory...\n");
    double (*bigArray)[d2][d3] = malloc(sizeof(double[d1][d2][d3]));

    printf("Done! Now setting values in allocated memory...\n");
    for (int i = 0; i < d1; i++){
        for (int j = 0; j < d2; j++){
            for (int k = 0; k < d3; k++){
                bigArray[i][j][k] = 0.0;
                printf("%f\n", bigArray[k][i][j]);
            }
        }
    }

    printf("Done! Ending program...\n");
    free(bigArray);
}

I've noticed that if I remove the printf() statement in the for loop, I don't notice any spike in memory use at all, so part of me is worried that this is more due to my use of printf() than anything else. However, the searching I've done seems to indicate that this may be due to the fact that my array isn't actually used for anything.

Apologies if my question isn't well-formed! I'm very new to C, as well as compiled languages in general, and mostly self taught. Happy to clarify things as necessary.

  • 1
    `the memory usage seems to instead slowly` `any spike in memory use at all` What tools are you using to monitor the memory usage? – KamilCuk Nov 03 '21 at 23:30
  • Your array indices don't look correct, but also that's unlikely to be the problem. Depending on how you're determining this to be an issue, be aware that whatever console where you're outputting all this stuff may be storing all that text in its scroll buffer. As a test, comment out the assignment, and just do `printf("%f\n", 0.0f);`. The other thing to consider is that your program really doesn't do anything with the array, so a smart compiler might completely optimize it out. – paddy Nov 03 '21 at 23:36

0 Answers0