c - 检测到堆栈粉碎,但 char 数组在限制范围内
问题描述
我试图了解我做错了什么。来自键盘的输入在字符数组限制内......即使输入是 8 个字符长,它也会引发错误。只要 char 长度为 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]);
推荐阅读
- java - MapStruct: How to do an @AfterMapping with optional parameters?
- java - getLifecycle().getState() 在 onStart() 之后仍然被创建
- python - How to manually throw a 503 error on scrapy?
- html-email - Outlook 表格过度扩展导致相邻内容换行
- java - Java - Cannot pull out min value in array
- python - 查找导致我的列成为“对象”类型而不是整数类型的错误数据
- maven - Maven looking for parent Jar instead of Pom in a multi-module project
- kendo-ui - Kendo Grid MVC 不能将列缩小到超出某个限制
- azure - 来自事件中心的数据未填充到 ADX 数据库中
- r - 如何在 R 中创建一个“情节”变量(在每个组中运行一个“for循环”?)