无法确定神秘段错误的原因

时间:2014-08-07 19:23:30

标签: c memory

以下代码是我正在努力在C中演示一些面向对象的编程思想。我现在遇到了一个段错误。没有警告或错误。小牛显然打破了valgrind,而gdb不再带有xcode,所以我用printfs调试了这个。

我想我已将错误跟踪到该行:

strcpy(b->genre, genre);

在函数“book_create”中。抱歉,如果这是愚蠢的话,C不是我花费大量时间的语言。

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

typedef struct book {
    char *title;
    char *author;
    char *genre;
    char *isbn;
    void (* set_title)(struct book *, char *);
    void (* print)(struct book *);
} * Book;

void book_set_title(Book self, char *title) {
    free(self->title);
    self->title = (char *) malloc(strlen(title) + 1);
    strcpy(self->title, title);
}

void book_print(Book b) {
    printf("Title: %s\nAuthor: %s\nGenre: %s\nISBN: %s\n", b->title, b->author, b->genre, b->isbn);
}

Book book_create(char *title, char *author, char *genre, char *isbn) {
    Book b = (Book) malloc(sizeof(Book));
    b->title = (char *) malloc(strlen(title) + 1);
    b->author = (char *) malloc(strlen(author) + 1);
    b->genre = (char *) malloc(strlen(genre) + 1);
    b->isbn = (char *) malloc(strlen(isbn) + 1);
    strcpy(b->title, title);
    strcpy(b->author, author);
    strcpy(b->genre, genre);
    strcpy(b->isbn, isbn);
    b->set_title = book_set_title;
    b->print = book_print;
    return b;
}

void book_destroy(Book b) {
    free(b->title);
    free(b->author);
    free(b->genre);
    free(b->isbn);
    free(b);
}

int main() {
    Book b = book_create("Harry Potter and the Sorcerer's Stone", "JK Rowling", "Fantasy", "123456");
    b->set_title(b, "Yo momma");
    b->print(b);
    book_destroy(b);
}

1 个答案:

答案 0 :(得分:4)

问题出在

Book b = (Book) malloc(sizeof(Book));

Book是指向struct book的指针,因此您分配的内存量太少。你应该使用:

struct book *b = malloc(sizeof *b);

在C语言中,最好不要转换malloc的结果,并且对结构体的typedefed指针可能会产生误导,如你所见。