0

I know that arrays can be created on the stack with syntax such as int array[5]; where the size must be known at compile time and array is a non modifiable l-value.

You can also create an array dynamically on the heap with new such as int* array = new int[5]; where it becomes possible to have a size of variable length and resize the array.

But what about something like:

int* array;
array[2] = 3;
cout << array[2] << endl;

Which creates an array on the stack that appears to be resizable because I can continue adding elements. The only other thing that should be kept track of is the size.

I wrote the above code accidentally in a project and I haven't seen it used ever. I not sure if it should be used at all, but I'm also not sure what's incorrect about it.

csguy
  • 1,354
  • 2
  • 17
  • 37
  • 2
    It's Undefined Behavior because `array` is an uninitialized pointer. Don't do that. – 1201ProgramAlarm Nov 19 '19 at 05:03
  • *Which creates an array on the stack "* - no. That's not what this code does. This code invokes *undefined behavior* precisely because it *doesn't* do what you state. – WhozCraig Nov 19 '19 at 05:27

2 Answers2

2

Writing int *array; does not create an array, it declares a pointer to some random memory page, and if you try to dereference this pointer, your program will receive “Segmentation fault” signal and will be shut down. Never use pointers without their proper initialization using addresses of existing objects, or allocated objects (using new), or functions/methods which return valid address.

Northsoft
  • 171
  • 4
  • 1
    To make it clear, segmentation fault is not guaranteed here, this is merely an undefined behaviour. Hovewer, this particular undefined behaviour leads to either segmentation fault or memory corruption in most cases. – Denis Sheremet Nov 19 '19 at 05:23
2

But what about something like:

int* array;
array[2] = 3;
cout << array[2] << endl;

Which creates an array on the stack that appears to be resizable because I can continue adding elements. The only other thing that should be kept track of is the size.

Nope. Unfortunately, C++ doesn't work like that. You need to allocate the array with new if you want to create a dynamic array with raw pointers.

This is because pointers only hold addresses. They don't actually guarantee that there is memory allocated at that address. Thus, you will need to allocate memory at an address if you want to use it.

If you want a dynamically allocated memory, you have other options including using std::vector, or std::unique_ptr, or std::shared_ptr. You can find more information on this and some examples at this question.