strcopy crashing c program

68 views Asked by At

My program takes name and age from command line arguments through name and stores each name and age as elements of a structure. My problem is strcpy crashing my program when I run it. Here is my code, I would appreciate any help that I can get.

 #include<stdio.h>
 #include<stdlib.h>
 #include<string.h>

 typedef struct {
     char name[80];
     int age;
 } person;

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

if (argc == 1 || argc % 2 == 0) {
    printf("Invalid arguments.\n Usage: %s name1 age1 name2 age2 ...", argv[0]);
    return 0;
}

person people[argc/2];
int i;

for (i = 0; i < argc; i++)
    strcpy(people[i].name, argv[i+1]);
1

There are 1 answers

1
winwaed On

The problem is with this loop here:

for (i = 0; i<argc; i++)
strcpy(people[i].name, argv[i+1]);

You have two out-of-range array references:

  1. You are looping from 0..argc-1, so you are referencing argv from 1..argc - ie. out of range.

  2. Also, you are creating an array of length argc/2 but you are referencing elements 0...argc - ie. another array overflow.

The loop should be something like:

for (i = 0; i<argc/2; i++)
  strcpy(people[i].name, argv[i*2+1]);