D
damian birchler
If I run the following I get a segmentation fault:
#define NAMELEN 15
#define NPERS 10
typedef struct pers {
char name[NAMELEN+1];
int money;
} pers_t;
char *my_fgets(char *s, int n, FILE *f) {
size_t i;
fgets(s, n+2, f);
i = strlen(s)-1;
if(s[(int)i] == '\n')
s[(int)i] = '\0';
return s;
}
int main(int argc, char *argv[]) {
int numOfPers;
pers_t pers[NPERS];
char s[NAMELEN+1];
FILE *in = fopen("gift1.in", "r");
/* initialize names for comparison */
for(i = 0; i < NPERS; i++)
bzero(pers.name, NAMELEN);
numOfPers = atoi(my_fgets(s, NAMELEN, in));
#ifdef DEBUG
printf("number of persons: %d\n", numOfPers);
my_fgets(pers[0].name, NAMELEN, in);
printf("person number 1 is %s\n", pers[0].name);
my_fgets(pers[1].name, NAMELEN, in);
printf("person number 2 is %s\n", pers[1].name);
#endif
for(i = 0; i < numOfPers; i++) {
my_fgets(pers.name, NAMELEN, in);
#ifdef DEBUG
printf("person number %d is %s", i+1, pers.name);
#endif
}
What seems so strange to me is that when I read the names in
'manually' it works perfectely, but when I try to read them in the for
loop the program crashes. I know that the error occurs in the for loop
because I won't see the result of the printf in the for loop. The
output is as follows:
number of persons: 5
person number 1 is dave
person number 2 is laura
Segmentation fault
Has anybody an idea of why this is?
Thanks
damian
#define NAMELEN 15
#define NPERS 10
typedef struct pers {
char name[NAMELEN+1];
int money;
} pers_t;
char *my_fgets(char *s, int n, FILE *f) {
size_t i;
fgets(s, n+2, f);
i = strlen(s)-1;
if(s[(int)i] == '\n')
s[(int)i] = '\0';
return s;
}
int main(int argc, char *argv[]) {
int numOfPers;
pers_t pers[NPERS];
char s[NAMELEN+1];
FILE *in = fopen("gift1.in", "r");
/* initialize names for comparison */
for(i = 0; i < NPERS; i++)
bzero(pers.name, NAMELEN);
numOfPers = atoi(my_fgets(s, NAMELEN, in));
#ifdef DEBUG
printf("number of persons: %d\n", numOfPers);
my_fgets(pers[0].name, NAMELEN, in);
printf("person number 1 is %s\n", pers[0].name);
my_fgets(pers[1].name, NAMELEN, in);
printf("person number 2 is %s\n", pers[1].name);
#endif
for(i = 0; i < numOfPers; i++) {
my_fgets(pers.name, NAMELEN, in);
#ifdef DEBUG
printf("person number %d is %s", i+1, pers.name);
#endif
}
What seems so strange to me is that when I read the names in
'manually' it works perfectely, but when I try to read them in the for
loop the program crashes. I know that the error occurs in the for loop
because I won't see the result of the printf in the for loop. The
output is as follows:
number of persons: 5
person number 1 is dave
person number 2 is laura
Segmentation fault
Has anybody an idea of why this is?
Thanks
damian