【问题标题】:stack smashing detected but the char array is within limits [closed]检测到堆栈粉碎但字符数组在限制范围内[关闭]
【发布时间】:2020-03-09 22:07:55
【问题描述】:

我试图了解我做错了什么。来自键盘的输入在 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(&amp;name[SLEN]); --> add_members(name);。前者错误地传递了指向数组末尾后一个字节的指针。

标签: c stack-smash


【解决方案1】:
add_members(&name[SLEN]);

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

add_members(name);add_members(&amp;name[0]);

【讨论】:

  • 谢谢你,辛苦了。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-07-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多