0

I have struct:

typedef struct _client
{
    char num[9];    
    char some[12];  
} person;

and I want enter values to that strings, I have that code and in the iteration its skip for the first input and go to the second one. why it skip from input to the num[9] string and goes to the some[12]?

int i;
person* arrClient = (person*)malloc(sizeof(person)*size);
for (i = 1; i <= size; i++)
{
    gets(arrClient[i].num);
    gets(arrClient[i].some);
}
anastaciu
  • 23,467
  • 7
  • 28
  • 53

1 Answers1

0

Acessing an array ouside it's bounds leads to undefined behavior.

The cycle for (i = 1; i <= size; i++) does just that, replace it with for (i = 0; i < size; i++).

gets() function is no longer part of C standard, it was removed since ISO C11 because of its vulnerability:

The first internet worm (the Morris Internet Worm) escaped about 30 years ago (1988-11-02), and it used gets() and a buffer overflow as one of its methods of propagating from system to system. The basic problem is that the function doesn't know how big the buffer is, so it continues reading until it finds a newline or encounters EOF, and may overflow the bounds of the buffer it was given.

So use:

fgets(arrClient[i].num, sizeof(arrClient[i].num), stdin);
arrClient[i].num[strcspn(arrClient[i].num, "\n")] = '\0'; //remove '\n'

The same for the second input.

anastaciu
  • 23,467
  • 7
  • 28
  • 53