首页 > 解决方案 > 检测到堆栈粉碎,但 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);
}

标签: cstack-smash

解决方案


add_members(&name[SLEN]);

这是不正确的,因为&name[SLEN]是数组末尾之后的字节。需要的是数组的开始。

add_members(name);或者add_members(&name[0]);


推荐阅读