Heap memory allocation

Hi there good people,
please look at my program down below,
the second case is behaving in a different way please clarify it for me.
thanks
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
  #include <iostream>

int main()
{
  // first case
  double *x = new double{10};
  double *w = new double{9};
  std::cout << x << '\n';
  std::cout << w << '\n';
  std::cout << w - 4 << " contains: \t" << *(w - 4) << '\n';

  // second case
  int *y = new int{10};
  double *z = new double{9};
  std::cout << y << '\n';
  std::cout << z << '\n';
  std::cout << z - 4 << " contains: \t" << *(z - 8) << '\n';
  
}
They're both broken, and you're wondering why?

> std::cout << w - 4 << " contains: \t" << *(w - 4)
Trying to access w out of bounds in the hope you will stumble into x is pure folly.

Even more so, trying to interpret an int as a floating point value.

thanks for replying @salem
I'm looking for an explanation, the first case I can access a previous location in memory.
the second one works if both y and z were int(s).
Also: am just trying to figure out which way does the stack-free store- initially grow.
Last edited on
Both cases trying to access outside the owned memory of the arrays is undefined behavior. You're "lucky" the program seems to run to completion instead of crashing.

https://en.cppreference.com/w/cpp/language/ub

Just because the language allows you to do potentially dangerous actions, such going out of bounds with an array, doesn't mean you should.

DON'T DO IT!

The second case is the bits of ints being interpreted as a double. More buggy code that results in undefined behavior.
am just trying to figure out which way does the stack-free store- initially grow.

Implementation defined. Dynamic arrays created "together" may or may not have their memory in contiguous blocks, or in what order the individual elements are laid out.

1
2
3
4
5
6
7
8
9
10
11
#include <iostream>

int main()
{
   double* a = new double[2];
   double* b = new double[2];

   std::cout << &a[0] << ' ' << &a[1] << '\n';

   std::cout << &b[0] << ' ' << &b[1] << '\n';
}

(The output of one run from MSVC):
00B40228 00B40230
00B35A18 00B35A20

The memory block for a is located on the heap AFTER the the memory block for b.

Anther run of the code and a is before b:
00B90580 00B90588
00B9DAC8 00B9DAD0

No guarantee the memory blocks are next to each other no matter what.

Other compilers MAY have a before b consistently and next to each other. Don't rely on that happening.
GCC (Code::Blocks):
0xe71770 0xe71778
0xe71790 0xe71798

Multiple runs with GCC, it allocates the same memory blocks each time. But they are not contiguous.
Topic archived. No new replies allowed.