Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>The array you are using is stack allocated:</p> <p>int memory[100];</p> <p>When the particular function scope exits (In this case main) or returns, the memory will be reclaimed and it will not leak. This is how stack allocated memory works. In this case you allocated 100 integers (32 bits each on my compiler) on the stack as opposed to on the heap. A heap allocation is just somewhere else in memory hopefully far far away from the stack. Anyways, heap allocated memory has a chance for leaking. Low level Plain Old Data allocated on the stack (like you wrote in your code) won't leak.</p> <p>The reason you got random values in your function was probably because you didn't initialize the data in the 'memory' array of integers. In release mode the application or the C runtime (in windows at least) will not take care of initializing that memory to a known base value. So the memory that is in the array is memory left over from last time the stack was using that memory. It could be a few milli-seconds old (most likely) to a few seconds old (less likely) to a few minutes old (way less likely). Anyways, it's considered garbage memory and it's to be avoided at all costs.</p> <p>The problem is we don't know what is in your function called print_memory. But if that function doesn't alter the memory in any ways, than that would explain why you are getting seemingly random values. You need to initialize those values to something first before using them. I like to declare my stack based buffers like this:</p> <p>int memory[100] = {0};</p> <p>That's a shortcut for the compiler to fill the entire array with zero's. It works for strings and any other basic data type too:</p> <p>char MyName[100] = {0}; float NoMoney[100] = {0};</p> <p>Not sure what compiler you are using, but if you are using a microsoft compiler with visual studio you should be just fine.</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload