Array of struct accepting more than defined, what's wrong?

0

In the code I created an array of type Pessoa containing only 2, but when it begins to iterate in the for loop and accesses index 2 and 3 the string continues without generating compile-time error nor execution. Is this behavior normal?

#include <stdio.h>
#include <windows.h>

typedef struct{
    int num;
}Pessoa;

Pessoa pessoa[2];

int main (int argc, char *argv[])
{
    const int count = 4;
    for(int i = 0; i < count; i += 1){
        pessoa[i].num = i;
    }
    for (int i = 0; i < count; i += 1)
    {
        printf("%d\n", pessoa[i].num);
    }
    system("pause");
    return 0;
}

Program exit

0
1
2
3
    
asked by anonymous 10.11.2017 / 02:01

2 answers

1

Completely normal. This is C, you do what you want and the language leaves. Of course it is corrupting memory and should not do this, but it is allowed. It works, but it is not right, in something a little more complex than this will give several problems. You are writing to a memory location that was not reserved for this array , there possibly would be something that would be lost.

In C is worth even more that it is not enough to make it work, it has to be right.

The ideal is not to use global variable, but in this case it makes no difference to be local, there will be memory corruption in any case, make the local variable does not solve anything. The only solution is to know what you are doing and not to let an area of memory that has not been allocated to what you want.

    
10.11.2017 / 02:26
-1

It's more or less normal.

Since you have put the person vector as a global, then it allows you to leave space allocating infinitely and gives a lot of room for things to get out of control. You can correct this by putting the variable as local in your main. So it prevents you from reading something that has not been declared in the function.

#include <stdio.h>
#include <windows.h>

typedef struct{
    int num;
}Pessoa;


int main (int argc, char *argv[])
{

    Pessoa pessoa[2];
    const int count = 4;
    int i;
    for(i = 0; i < count; i += 1){
        pessoa[i].num = i;
    }
    for (i = 0; i < count; i += 1)
    {
        printf("%d\n", pessoa[i].num);
    }
    system("pause");
    return 0;
}

Output:

0
1

And here's the tip: Avoid using global variables.

    
10.11.2017 / 09:32