-7

Assuming my pointer is not pointing to an array, how is this block:

int *ptr_a;

ptr_a = new int;
*ptr_a = 1;

different compared with:

int *ptr_a = 1;

Is there a difference in memory allocation and when would I use one over the other?

bryan2402
  • 1
  • 1
  • 1
  • when your stack is limited is one answer. even then, using smart pointers is the way move forward. also `int *ptr_a = 1;` more likely suppose to be just `int ptr_a = 1;` – Yucel_K Oct 07 '18 at 09:34
  • Increase your compiler's warning/error level - live: https://godbolt.org/z/n5Ng9y – Richard Critten Oct 07 '18 at 09:34
  • 3
    `int *ptr_a = 1;` is not a valid C++. – HolyBlackCat Oct 07 '18 at 09:36
  • But since you can't directly assign an integer to the pointer, rather makes the question moot. – Eljay Oct 07 '18 at 11:26
  • Possible duplicate of [Stack, Static, and Heap in C++](https://stackoverflow.com/questions/408670/stack-static-and-heap-in-c) –  Oct 07 '18 at 12:07

1 Answers1

7

int *ptr_a = 1;doesn't create a new int, this creates a pointer ptr_a and assigns a value of 1 to it, meaning that this pointer will point to the address 0x00000001. It's not an integer. If you try to use the pointer later with *ptr_a = 2, you will get a segmentation fault because the pointer doesn't point to an allocated memory space (in this precise case, it points to kernel memory, which is a no-no).

A good principle nowadays is to used std::unique_ptr<int> ptr_a = std::make_unique<int>(1)which will allocate a new int with a value of 1 and deallocate the memory once ptr_a gets out of scope.

Matthieu Brucher
  • 21,634
  • 7
  • 38
  • 62
  • 3
    I'd suggest a good principle is to use `int a` if a single `int` is needed rather than mucking around with a pointer to a single dynamically allocated `int`, or a `std::unique_ptr`. If you need a arbitrary-sized collection of `int`s, use a suitable standard container such as `std::vector`. – Peter Oct 07 '18 at 09:56