1

I tried to insert an element in an array and it failed with array index out of bounds

I tried in C# it failed it works fine in c

int[] LA = {1,3,5,7,8};
int item = 10, k = 3, n = 5;
int i = 0, j = n;   
n = n + 1;
while( j >= k) 
{
    LA[j+1] = LA[j];
    j = j - 1;
}
LA[k] = item;

but it works in c

int LA[] = {1,3,5,7,8};
int item = 10, k = 3, n = 5;
int i = 0, j = n;
n = n + 1;
while( j >= k) {
    printf("j+1 =%d",j+1);
    LA[j+1] = LA[j];
    j = j - 1;
}

Can someone please explain why this is? and what about other languages will it keep varying? Thanks.

Many answers say it doesn't work in c so i have uploaded an image ![enter image description here]1

12
  • 1
    @DmitryBychenko in this case, the error is that he's reading from LA[6], so using a List<T> won't help. Commented Feb 14, 2019 at 11:41
  • 1
    btw: I can "fix" the C# too, look! int* LA = stackalloc int[] { 1, 3, 5, 7, 8 }; - done! this will also "work" for the same reasons (meaning: it is equally broken) - the reasons here being: your C array isn't bound-checked (just like my C# pointer); you have then accessed memory past the end of the defined range - that might be unused memory, it could be something really important, it could be an invalid page; at that point: your code is just broken Commented Feb 14, 2019 at 11:48
  • 1
    C# has fewer nasal demons. This is something that makes C# easier; you get an error message now rather than a really hard to find bug weeks later. Commented Feb 14, 2019 at 11:55
  • 1
    @nevas C arrays (which, when indexed into, are essentially the same as pointer expressions) are indeed not bounds checked; this is a feature of the language and that concept; if you want a bounds-checked type : don't use raw arrays (/pointers) Commented Feb 14, 2019 at 11:58
  • 1
    @nevas: Array accesses in C are not bounds checked. Attempting to access an array element outside the range of the array leads to undefined behavior, meaning there’s no requirement on the compiler or runtime environment to do anything in particular. Your code may appear to work as intended, or it may corrupt other data, or it may crash outright. Commented Feb 14, 2019 at 12:36

3 Answers 3

5

Oh no, this doesn't "work", that looks like pretty blatant out of bounds writing, and thus you're getting undefined behavior. You cannot dynamically grow an array in C, they are statically sized at the point of "creation".

Note that C doesn't say that doing undefined things will result in any particular measurable result[*], so it can appear to do the intended thing, but still be completely broken.

[*]: That is what "undefined" means: there is no definition of what is going to happen. Some people seem to interpret it as "we're going to get the error handler for triggering that thing they call 'undefined behavior'", but that is not true. Anything could happen, anything.

Sign up to request clarification or add additional context in comments.

3 Comments

"Anything could happen, anything". Undefined does not mean anything can happen. There are a set of things that could possibly happen when you read outside the bounds of an array. Your computer turning into a rabbit is not one of them. :)
@MineR This is writing, not reading. Also, of course the computer can't start violating laws of physics all of a sudden, but the point is that the C standard doesn't limit what could happen. You can't reason about it, unless you know what code the compiler happened to generate for this case, and how the underlying machine acts when the actual instructions generated execute under these conditions.
OR WORSE. U.B. means that it can work fine during decades and then fail, without any apparent reason.
2

On the first iteration of the loop, j = n = 5. However you're reading from LA[j], which is LA[5]. LA only 5 elements, so you can read from and write to LA[0] to LA[4]. You're then trying to write to LA[6], which is even further beyond the bounds of the array!

Fix your algorithm - you're not allowed to read from or write to elements outside of the bounds of the array.

The reason this "works" in C is that C isn't checking whether you're reading or writing outside of the bounds of the array. You're actually reading some random value that's sitting in memory beyond the end of your array. Technically this is invoking undefined behaviour, and anything at all could happen.

Comments

0

Instead of array you can insert item easily using C# ArrayList or List like:

 static void Main(string[] args)
 {
     ArrayList LA = new ArrayList() { 1, 3, 5, 7, 8 };
     Console.WriteLine("The Original array elements are:" + string.Join(",", LA.ToArray()));

     int item = 10, k = 3;
     LA.Insert(k, item);
     Console.WriteLine("The array elements after insertion:" + string.Join(",", LA.ToArray()));

     Console.ReadKey();
 }

Dotnetfiddle : https://dotnetfiddle.net/ISzZPz

9 Comments

Please don't use ArrayList - it was outdated in C# 2, 13 years ago! Use a generic List<T>. Also note that your suggestion combined with his code still crashes.
No. It doesn't crashes. I execute it in a console application and pest it here.
As in, if you try and use the OP's original algorithm - LA[j+1] = LA[j]; etc - that will crash, because you're still doing an out-of-bounds array read. Your answer ignores this, by throwing away the OP's original algorithm and writing something else instead.
Very funny argument :) why you want to use LA[j+1] = LA[j]; with ArrayList. ArrayList has its own function for insertion. Anyway my focus is on the solution of this problem using C# not the output. Because you can represent this output in too many ways in C#.
@canton7 Other thing is, why you discourage someone using ArrayList. According to the problem domain, if somebody needs using multiple type together like string and int, in that case he has to be use ArrayList. Because you can't use multiple type using List.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.