Struct array accepting more than defined, what’s wrong?

Asked

Viewed 47 times

0

In the code I created a array of the kind Pessoa containing only 2, but when it starts to iterate on the for loop and accesses index 2 and 3 the condigo continues without generating error at compile or run time. This behavior is 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;
}

Exit from the program

0
1
2
3
  • Did any of the answers solve your question? Do you think you can accept one of them? Check out the [tour] how to do this, if you haven’t already. You would help the community by identifying what was the best solution for you. You can accept only one of them. But you can vote on any question or answer you find useful on the entire site (when you have enough score).

2 answers

2

Completely normal. That’s C, you do what you want and the language leaves. Of course you’re corrupting the memory and you shouldn’t be doing that, but it’s allowed. It works, but it’s not right, in something a little more complex that this will give several problems. You are writing in a memory site that has not been reserved for this array, there would possibly have something that would be lost.

In C is worth even more the maximum that it is not enough to make it work, you have 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 either case, making the local variable does not solve the problem. The only solution is to know what you are doing and not let access an area of memory that has not been allocated to what you want.

-1

It’s kind of normal.

Because you put the person vector as global, then it allows you to go around allocating space infinitely and gives plenty of room for things to get out of hand. You can fix this by placing the variable as the location 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;
}

Exit:

0
1

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

Browser other questions tagged

You are not signed in. Login or sign up in order to post.