0

Let's say we have the following array: int arr[] = {0, 1, 2, 3, 4};

And then we type: arr[5] = -23;

What exactly happens? Does this work at all, or does it make an error? If we were to draw out the stack memory for this program (assuming these are the only defined values), what would it look like?

TL;DR: Does arr[5] work? If so, does this make an entirely new array of size 6, or does it just internally have a pointer from arr[4] to arr[5]?

TheAkashain
  • 29
  • 1
  • 6
  • 2
    Writing outside the bounds of the array is undefined behavior, you shouldn't do it. – anastaciu Oct 06 '20 at 22:11
  • 2
    *"What exactly happens"* unpredictable. That code invokes *undefined behavior*. You literally cannot say definitively what will transpire (if anything). Thus the reason to avoid UB. There's enough chaos around us already; we don't need to invent more. – WhozCraig Oct 06 '20 at 22:12

2 Answers2

1

You've written a buffer overflow. You're trying to write to memory that's beyond what has been assigned to you for arr.

The actual consequences of this are undefined. Since arr is probably stack-allocated, you've most likely overwrritten whatever variables are on the stack above arr.

does this make an entirely new array of size 6

Nope. You'll need to allocate yourself a larger buffer, copy the existing elements to it, then append your new element to it.

Alexander
  • 59,041
  • 12
  • 98
  • 151
  • Oh! Thank you so much! I was trying to draw out the memory stack for this program, and ended up horribly confused. – TheAkashain Oct 06 '20 at 22:13
  • 2
    Since it's undefined behavior, it actually _can_ make an entirely new array of size 6, though I wouldn't depend on it :) I recommend reading about undefined behavior a bit (to OP). – Fatih BAKIR Oct 06 '20 at 22:14
  • @FatihBAKIR Thank you! For my current purposes, the answer here solves my problem, but now I'm really curious about undefined behaviour in C, so I may just look into it! – TheAkashain Oct 06 '20 at 22:22
  • 1
    @TheAkashain, you can read all about it in the C standard, [C11 N1570 Draft §3.4.3](https://port70.net/~nsz/c/c11/n1570.html#3.4.3) – anastaciu Oct 06 '20 at 22:30
1

arr[5] means you only allocated 5 spots of memory. If you write to the 6th element, then you risk overwriting other data in memory.

In plain C, there is no such thing as appending an array. You either have to copy it to a new array, or you will need more complex storage-constructs.

Opifex
  • 362
  • 4
  • 15
  • 1
    @anastaciu Okay, OP specified `int` in his question. I missed that. I wanted my answer to be generic for all datatypes, but should probably have said "memory locations" instead of bytes. – Opifex Oct 07 '20 at 07:25
  • 1
    Thanks for pointing that out. – Opifex Oct 07 '20 at 08:44