检测到堆栈粉碎但字符数组在限制范围内
stack smashing detected but the char array is within limits
我正在努力了解我做错了什么。来自键盘的输入在字符数组限制内...
即使输入是 8 个字符长,它也会抛出错误。只要字符长度为 6 个字符,它就可以正常工作。
这是我的代码(我可以发誓它在 1 小时前一直有效)
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
#include "functions.h"
#define SLEN 81
#define FILE_NAME "../database.txt"
void add_members(char *name);
int main(void)
{
char name[SLEN], surname[SLEN], address[SLEN];
unsigned int dob, start_date, end_date;
add_members(&name[SLEN]);
return 0;
}
void add_members(char *name)
{
FILE *file;
if ((file = fopen(FILE_NAME, "a")) == NULL)
{
printf("cant open file %s\n", FILE_NAME);
exit(EXIT_FAILURE);
}
fputs("Insert FIRST NAME: ", stdout);
fgets(name, SLEN, stdin); // appears the problem to be here
check_string(name); // this is defined in another file
fputs(name, file);
printf("Name added to database: %s\n", name);
if (fclose(file) != 0)
printf("error in closing file %s\n", FILE_NAME);
printf("File: %s closed\n", FILE_NAME);
}
add_members(&name[SLEN]);
这是不正确的,因为 &name[SLEN]
是数组末尾之后的字节。需要的是数组的开头。
add_members(name);
或 add_members(&name[0]);
我正在努力了解我做错了什么。来自键盘的输入在字符数组限制内... 即使输入是 8 个字符长,它也会抛出错误。只要字符长度为 6 个字符,它就可以正常工作。
这是我的代码(我可以发誓它在 1 小时前一直有效)
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
#include "functions.h"
#define SLEN 81
#define FILE_NAME "../database.txt"
void add_members(char *name);
int main(void)
{
char name[SLEN], surname[SLEN], address[SLEN];
unsigned int dob, start_date, end_date;
add_members(&name[SLEN]);
return 0;
}
void add_members(char *name)
{
FILE *file;
if ((file = fopen(FILE_NAME, "a")) == NULL)
{
printf("cant open file %s\n", FILE_NAME);
exit(EXIT_FAILURE);
}
fputs("Insert FIRST NAME: ", stdout);
fgets(name, SLEN, stdin); // appears the problem to be here
check_string(name); // this is defined in another file
fputs(name, file);
printf("Name added to database: %s\n", name);
if (fclose(file) != 0)
printf("error in closing file %s\n", FILE_NAME);
printf("File: %s closed\n", FILE_NAME);
}
add_members(&name[SLEN]);
这是不正确的,因为 &name[SLEN]
是数组末尾之后的字节。需要的是数组的开头。
add_members(name);
或 add_members(&name[0]);