Z
Z
Zuoya2020-10-27 17:55:23
C++ / C#
Zuoya, 2020-10-27 17:55:23

Why is it possible to put more than N elements in an array of size N?

there is an array I need to make a slice of this array. for this I wrote a function
char az [] = "123456789-"

char* get_slice(char *input,size_t input_len,int a, int b ){
    if ( a >= input_len || b >= input_len) { return NULL;}
    int j,i,out_leng = (0);
    char *out = malloc(sizeof(char)*out_leng);
    
    for (j= 0,i = a; i <= b; i++,j++) {
      
        out[j] = input[i];
    }

    printf("leng = %d\n",j);
   
    return out;
}

it seems to work, but I set the size of the out array to 0 and for some reason you can copy data into it.
here is a complete example
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
char* get_slice(char *input,size_t input_len,int a, int b );
char* get_slice(char *input,size_t input_len,int a, int b ){
    if ( a >= input_len || b >= input_len) { return NULL;}
    int j,i,out_leng = (0); // out_leng = b -a;
    char *out = malloc(sizeof(char)*out_leng);
    
    for (j= 0,i = a; i <= b; i++,j++) {
      
        out[j] = input[i];
    }

    printf("leng = %d\n",j);
   
    return out;
}

int main(int argc, char const *argv[])
{
    char az [10] = "123456789-";
    int l = 7;
    // новый массив должен иметь данные от 2 до 5 индекса массива az
    char *z = get_slice(az,sizeof(az),2,5);
    if (z == NULL) {
        puts("ERR");
    }else
    {
        printf("%s",z);
    }
    return 0;
}

Answer the question

In order to leave comments, you need to log in

1 answer(s)
1
15432, 2020-10-27
@Zuoya

Because in the C language, you yourself have to control the work with memory and make sure that there is no write out of the array, stack overflow, etc.
In this case, due to such a recording beyond the limits of the permissible, any glitches are possible up to the crash of the program.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question