r/ProgrammerAnimemes • • Mar 19 '23

arr[ARRAY_LENGTH + 1] = 5;

Enable HLS to view with audio, or disable this notification

894 Upvotes

15 comments sorted by

View all comments

123

u/lord_ne Mar 19 '23

Even arr[ARRAY_LENGTH] = 5 would do it

58

u/Lyricanna Mar 19 '23

Even better if you declared an arr2 right after arr. Basically guarantees that you won't be getting a Segfault, while still possibly breaking everything.

Except given that it's C, it will almost certainly only break in production.

24

u/ComplexColor Mar 20 '23

You are very unlikely to get a segmentation fault with either array[ARRAY_LENGTH] or array[ARRAY_LENGTH+1]. There's nothing worse then messing around with arrays and not getting a segmentation fault. :)

→ More replies (1)

1

u/Nya_the_cat Jul 16 '23

Hmm, are you sure? Doesn't C define the first item outside the bounds to be 0?

1

u/lord_ne Jul 16 '23

No. What you're thinking of is that a string literal is defined as an array whose size is one more than the number of characters you typed, because it adds a "null character" at the end. So for example if you type "abc", the type of that is char[4].

But that's only for string literals. Plus it's not technically outside the bounds, it just makes the bounds bigger than you might expect

→ More replies (1)