c - 段错误(核心转储)

标签 c segmentation-fault

我是C语言新手,现在正在学习结构。 这试图创建一个完整的小程序来管理数据库。

#include <stdio.h>
#include <assert.h>
#include <stdlib.h>
#include <errno.h>
#include <string.h>

#define MAX_DATA 512
#define MAX_ROWS 100

struct Address {
    int id;
    int set;
    char name[MAX_DATA];
    char email[MAX_DATA];
};

struct Database {
    struct Address rows[MAX_ROWS];
};

struct Connection {
    FILE *file;
    struct Database *db;
};

void die(const char *message)
{
    if(errno) {
        perror(message);
    } else {
        printf("ERROR: %s\n", message);
    }

    exit(1);
}

void Address_print(struct Address *addr)
{
    printf("%d %s %s\n",
            addr->id, addr->name, addr->email);
}

void Database_load(struct Connection *conn)
{
    int rc = fread(conn->db, sizeof(struct Database), 1, conn->file);
    if(rc != 1) die("Failed to load database.");
}

struct Connection *Database_open(const char *filename, char mode)
{
    struct Connection *conn = malloc(sizeof(struct Connection));
    if(!conn) die("Memory error");

    conn->db = malloc(sizeof(struct Database));
    if(!conn->db) die("Memory error");

    if(mode == 'c') {
        conn->file = fopen(filename, "w");
    } else {
        conn->file = fopen(filename, "r+");

        if(conn->file) {
            Database_load(conn);
        }
    }

    if(!conn->file) die("Failed to open the file");

    return conn;
}

void Database_close(struct Connection *conn)
{
    if(conn) {
        if(conn->file) fclose(conn->file);
        if(conn->db) free(conn->db);
        free(conn);
    }
}

void Database_write(struct Connection *conn)
{
    rewind(conn->file);

    int rc = fwrite(conn->db, sizeof(struct Database), 1, conn->file);
    if(rc != 1) die("Failed to write database.");

    rc = fflush(conn->file);
    if(rc == -1) die("Cannot flush database.");
}

void Database_create(struct Connection *conn)
{
    int i = 0;

    for(i = 0; i < MAX_ROWS; i++) {
        // make a prototype to initialize it
        struct Address addr = {.id = i, .set = 0};
        // then just assign it
        conn->db->rows[i] = addr;
    }
}

void Database_set(struct Connection *conn, int id, const char *name, const char *email)
{
    addr->set = 1;

    char *res = strncpy(addr->name, name, MAX_DATA);

    addr->name[MAX_DATA] = '\n';
    if(!res) die("Name copy failed");

    res = strncpy(addr->email, email, MAX_DATA);
    addr->email[MAX_DATA] = '\n';
    if(!res) die("Email copy failed");

}

void Database_get(struct Connection *conn, int id)
{
    struct Address *addr = &conn->db->rows[id];

    if(addr->set) {
        Address_print(addr);
    } else {
        die("ID is not set");
    }
}

void Database_delete(struct Connection *conn, int id)
{
    struct Address addr = {.id = id, .set = 0};
    conn->db->rows[id] = addr;
}

void Database_list(struct Connection *conn)
{
    int i = 0;
    struct Database *db = conn->db;

    for(i = 0; i < MAX_ROWS; i++) {
        struct Address *cur = &db->rows[i];

        if(cur->set) {
            Address_print(cur);
        }
    }
}

int main(int argc, char *argv[])
{
    if(argc < 3) die("USAGE: ex17 <dbfile> <action> [action params]");

    char *filename = argv[1];
    char action = argv[2][0];
    struct Connection *conn = Database_open(filename, action);
    int id = 0;

    if(argc > 3) id = atoi(argv[3]);
    if(id >= MAX_ROWS) die("There's not that many records.");

    switch(action) {
        case 'c':
            Database_create(conn);
            Database_write(conn);
            break;

        case 'g':
            if(argc != 4) die("Need an id to get");

            Database_get(conn, id);
            break;

        case 's':
            if(argc != 6) die("Need id, name, email to set");

            Database_set(conn, id, argv[4], argv[5]);
            Database_write(conn);
            break;

        case 'd':
            if(argc != 4) die("Need id to delete");

            Database_delete(conn, id);
            Database_write(conn);
            break;

        case 'l':
            Database_list(conn);
            break;
        default:
            die("Invalid action, only: c=create, g=get, s=set, d=del, l=list");
    }

    Database_close(conn);

    return 0;
}

应该是这样的:

$ make ex17
cc -Wall -g    ex17.c   -o ex17
$ ./ex17 db.dat c
$ ./ex17 db.dat s 1 someone someemail
$
$ ./ex17 db.dat l
1 someone someemail

但我收到此错误消息:段错误(核心已转储)。

$ make ex17
cc -Wall -g    ex17.c   -o ex17
$ ./ex17 db.dat c
$ ./ex17 db.dat s 1 someone someemail
Segmentation fault (core dumped)

我认为“Database_set”中有问题。我想解决这个问题,但我不能。我想知道我做错了什么。感谢对此错误的任何帮助。

最佳答案

在行

void Database_set(struct Connection *conn, int id, const char *name, const char *email)
{
    addr->set = 1;

你在哪里定义addr?我什至不明白这是如何编译的...

大概您需要统计数据库中有效记录的数量,并在添加新记录时将 addr 指向第一个未使用的记录。这需要更新数据库结构以及用于添加和删除的函数。或者您循环访问数据库到第一个未设置的地址。无论哪种方式,您的函数都需要声明 addr 并将其设置为有用的值,然后再将其用作指针。

以下代码行可能会有所帮助(这些代码是 Database_set 函数的第一行):

struct Address *addr;
int ii=0;
while(conn->db->rows[ii].set) ii++;
addr = conn->db->rows + ii;
addr->set = 1;
addr->id = id;

您还需要进行 craig65535 所示的更改。您的代码很可能存在其他问题,但是通过这些添加,我可以执行您在问题中给出的指令;它编译,运行,不提示。这是一个开始。 哦 - 它能够使用 l 命令列出数据库...

关于c - 段错误(核心转储),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15870762/

相关文章:

c - 共享内存中的指针

c - 如何根据用户在 C 中的输入停止程序

c - 我们应该在 C 中使用 exit() 吗?

c - 我一直在尝试编写一个程序将十进制转换为二进制,我不知道我的代码有什么问题?我正在使用代码块

c - malloc() 调用函数 - 段错误 : 11

c - 需要帮助弄清楚为什么 strtok 导致段错误,它不能使用 const char* 参数吗?

c - 测量使用 Clang/LLVM 生成的函数的大小?

c - 错误: misuse of undefined type 'struct IntArray'

objective-c - Objective-C 中的段错误是什么?

c - 循环中的execl和wget命令