Auto resize array initialized by auto count?

So. At the moment I am teaching programming 1 to some college level students. And I specifically told them to go outside and look online for links, especially the pieces of data that I am covering now. Today, one student sent me an email with a link to tutorialspoint.com and asked about this piece of code that he pulled from there:

#include <stdio.h>

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

   printf("The original array elements are :\n");

   for(i = 0; i<n; i++) {
      printf("LA[%d] = %d \n", i, LA[i]);
   }

   n = n + 1;

   while( j >= k) {
      LA[j+1] = LA[j];
      j = j - 1;
   }

   LA[k] = item;

    printf("The array elements after insertion :\n");

   for(i = 0; i<n; i++) {
      printf("LA[%d] = %d \n", i, LA[i]);
   }
}

Now, not knowing where exactly, I don’t know exactly how they described it, but, obviously, this is an insertion into the array of values ​​in the index k, shuffled up from k.

Now he asked about what I told my students that when doing something like:

int arr[] = {1,2,3,4};

, . 4 . , , :

int likethis[5]; 
int orthis[] = {1,2,3,4};
int orlikeso[MAX_ARR_SIZE];

, , ( , ).

- , , - , .

, LA 6 . , . , , , GCC. , ? - LA [5] ?

: , C ? GCC? , C 80- , , , , , LA. S.O.

+4
4

- , , - , .

, . undefined, 5 .

, .

" " . "". , .

, C, (, valgrind) . , , .

: , , undefined C, " , " .

+13

, undefined, , , .

- , , , .

+2

, C. , - ". ( strncpy C )

, LA , , :

#include <stdio.h>

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

    printf("The original array elements are :\n");
    printf("Number of elements in LA = %ld\n",(sizeof(LA)/sizeof(int)));

    for(i = 0; i<n; i++) {
        printf("LA[%d] = %d \n", i, LA[i]);
    }

    n = n + 1;

    while( j >= k) {
        LA[j+1] = LA[j];
        j = j - 1;
    }

    LA[k] = item;

    printf("The array elements after insertion :\n");

    for(i = 0; i<n; i++) {
        printf("LA[%d] = %d \n", i, LA[i]);
    }
    printf("Number of elements in LA = %ld\n",(sizeof(LA)/sizeof(int)));
}
+1
source

To answer your question, the code is simply invalid. The array overflows, but the error is not visible (however, if you enable compiler size optimization, it should improve the likelihood that this code will work).

To help you detect overflow, I suggest you run the code with Valgrind, as it will detect overflow for you.

edit: I ran Valgrind with memcheck and it did not notice this overflow. Amazing to me.

+1
source

Source: https://habr.com/ru/post/1664174/


All Articles