2

I got the following code over the Internet to insert an element in an array. My question is that "how could the size of the array can be incremented especially​ at first insertion and garbage is printed at every execution of printing for loop?". I'm also eager to get details on the error I get.

The code is

#include <stdio.h>
void main() 
{
    int k = 3, n = 5, i = 0, j = n;
    int LA[] = {1,3,5,7,8};
    printf("The original array elements are :\n");
    for(i = 0; i<n; i++) {
        printf("%d ",LA[i]);
    }
    n = n + 1;
    while( j >= k){
        LA[j+1] = LA[j];
        j = j - 1;
    }
    LA[k] = 10;
    printf("\nThe array elements after insertion1 :\n");
    for(i = 0; i<n; i++) {
        printf("%d ",LA[i]);
    }
    n = n + 1;
    while( j >= k){
        LA[j+1] = LA[j];
        j = j - 1;
    }
    LA[k] = 20;
    printf("\nThe array elements after insertion2 :\n");
    for(i = 0; i<n; i++) {
        printf("%d ",LA[i]);
    }
    n = n + 1;
    while( j >= k){
        LA[j+1] = LA[j];
        j = j - 1;
    }
    LA[k] = 30;
    printf("\nThe array elements after insertion3 :\n");
    for(i = 0; i<n; i++) {
        printf("%d ",LA[i]);
    }
}

The output is

The original array elements are :
1 3 5 7 8 
The array elements after insertion1 :
1 3 5 10 7 8 
The array elements after insertion2 :
1 3 5 20 7 8 2087809280 
The array elements after insertion3 :
*** stack smashing detected ***: ./a.out terminated
1 3 5 30 7 8 2087809280 -1077687568 Aborted (core dumped)

thanks for ur time.

Revaapriyan
  • 309
  • 2
  • 4
  • 20
  • 1
    Details of the error are that you corrupted the stack. Look up "smashing the stack for fun and profit". (disclaimer: I haven't read the code yet) – Millie Smith Jun 14 '17 at 16:47

1 Answers1

9

You have declared an array LA of size 5.

 int LA[] = {1,3,5,7,8};

Later on, your code tried to add additional elements, however, the size of LA is still 5, so you are placing values in array space you do not have allocated.

Chances are then, that the array is being allocated on the stack, and since you are writing to areas that aren't part of the array, you are messing up the stack.

Any printf accessing indexes beyond the LA size are going to be whatever happens to be at that position in memory

lostbard
  • 5,065
  • 1
  • 15
  • 17
  • 1
    I think the program only writes off the end of the array during the first while loop. Then, he's just formatting printf from off the end of the array. Then main tries to exit and realizes the stack is corrupt (only four bytes though). – Millie Smith Jun 14 '17 at 16:56