下面的代码是我在C语言中演示一些面向对象编程思想的代码,不过我得到了一个segfault。没有警告或错误。小牛显然打破了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);
}

最佳答案

问题就在这条线上

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

Book是指向struct book的指针,因此分配的内存太少。您应该使用:
struct book *b = malloc(sizeof *b);

在C语言中,最好不要强制转换malloc的结果,而且指向结构的typedef指针可能会误导您,如您所见。

09-10 09:33
查看更多