0
typedef struct {
int serial_no;
char s_name[100];
char s_street[50];
char s_town[20];
int s_speaker_no;
int max_no_teachers;
int no_applied_teachers;
} type_seminar;


void add_seminar() {
int seminar_number, temp_int;
char *temp_string;
temp_string = (char*) malloc(100 * sizeof(char));

FILE *f_sem;
FILE *f_school;
f_sem = fopen("seminars.bin", "a");
f_school = fopen("school_list.txt", "r");

fgets(temp_string, 10, f_school);
seminar_number = (atoi(temp_string) + 1);

type_seminar *temp_s = (type_seminar*) malloc(sizeof(type_seminar));
temp_s->serial_no = seminar_number;
temp_s->no_applied_teachers = 0;
temp_s->s_speaker_no = 0;

printf("Enter the seminar title: \n");
fgets(temp_string, sizeof temp_string, stdin);
strcpy(temp_s->s_name, temp_string);

printf("Enter the seminar address(street and house number): \n");
fgets(temp_string, sizeof temp_string, stdin);
strcpy(temp_s->s_street, temp_string);

printf("Enter the town (where the seminar will be held) : \n");
fgets(temp_string, sizeof temp_string, stdin);
strcpy(temp_s->s_town, temp_string);

printf("Enter the maximum number of the seminar participants : \n");
fgets(temp_string, sizeof temp_string, stdin);
temp_int = (atoi(temp_string));
temp_s->max_no_teachers = temp_int;

free(temp_s);
free(temp_string);
fclose(f_school);
fclose(f_sem);
}

每次我运行该函数时,都会跳过用户应该输入研讨会标题的第一个 fgets()。我认为从 txt 文件中读取的 previus fgets() 在缓冲区中留下了一些东西?我不知道如何解决这个问题......另外,我是 C 和一般编程的新手,所以如果它是显而易见的......对不起:/

4

1 回答 1

3

使用fgets以避免缓冲区溢出的荣誉,但你并不完全在那里:

char *temp_string;
:
temp_string = (char*) malloc(100 * sizeof(char));
:
fgets(temp_string, sizeof temp_string, stdin);

的大小temp_stringchar 指针的大小,而不是您分配的缓冲区的大小。这意味着您很可能最多只读取四个(或者如果您有 64 位指针,可能是八个)字符,然后其余的留在输入流中。

您应该使用缓冲区的大小(100,尽管作为定义的常量而不是硬编码的值会更好)。

或者,看看这个 getLine 例程,它处理了很多边缘情况。


而且,顺便说一句,您不需要乘以,sizeof(char)因为根据定义总是可以保证1- 乘以只会阻塞您的源代码。

您也不应该从中转换返回值,malloc因为它可以隐藏某些细微的错误。C 非常有能力将thevoid *` 返回值隐式转换为任何其他指针类型。

您应该注意的另一件事是:即使您fgets用于保护temp_string缓冲区免于溢出,也没有为您的strcpy函数设置类似的保护。

这意味着它将允许您输入一个 80 个字符的城镇名称,然后它将把它不应该触及的记忆吹到strcpy20 个字符的结构字段中。

于 2013-02-05T02:09:58.120 回答