简体   繁体   English

使用malloc的分段错误

[英]segmentation fault using malloc

I'm new to C, so this may be a silly question to ask: 我是C的新手,所以这可能是一个愚蠢的问题:

What I want to do here is to input the data to the array of pointers to a structure and then print it out. 我在这里要做的是将数据输入到指向结构的指针数组,然后将其打印出来。 But I get a segmentation fault when running into the insert function. 但是,在运行插入功能时遇到了分段错误。

Below is my code 下面是我的代码

common.h COMMON.H

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

typedef struct book * Book;

struct book{
    int id;
    char *name;
};

extern int b_insert(Book *b, int id, char *name);
extern int b_print(Book books[], int len);

insert.c insert.c

#include "common.h"

int b_insert(Book *b, int id, char *name){
    Book p;
    p = (Book)malloc(sizeof(struct book));
    p->id = id;
    strcpy(p->name, name);

    *b = p;
    printf("success insert book:\n");
    printf("\tID: %d Name: %s\n", (*b)->id, (*b)->name);

    return 0;

}


int b_print(Book books[], int len){
    int i;
    printf("Book List\n");
    for(i=0; i<len; i++){
        printf("books[%d] = ID: %d, Name: %s\n", i, books[i]->id, books[i]->name);
    }
    return 0;

}

main.c main.c中

#include "common.h"
#define MAX 2

int main(){
    Book books[MAX];
    Book *b=books;
    int i;
    int id;
    char name[10];




    for(i=0; i<MAX; i++){
        printf("please input new books info\n");
        printf("ID: ");
        scanf("%d", &id);
        printf("Name: ");
        scanf("%s", name);
        if(b_insert(b, id, name) == -1){
            printf("fail to insert\n");
        }
        b++;
    }

    b_print(books, MAX);

    return 0;
}

Main problem: 主要问题:

Allocate memory for p->name before using 使用前为p->name分配内存

strcpy(p->name, name);

using malloc : 使用malloc

p->name = malloc(10); //Or some other size

Other problems: 其他问题:

  1. Remove the cast here: 在此处删除演员表:

     p = (Book)malloc(sizeof(struct book)); 

    Why? 为什么? Here is the answer 这是答案

  2. if(b_insert(b, id, name) == -1){ will never be true. if(b_insert(b, id, name) == -1){永远不会为真。
  3. Check the result of malloc to check if it was successful in allocating memory. 检查malloc的结果以检查它是否成功分配了内存。
  4. Check the return value of all the scanf s to see if it was successful in scanning data. 检查所有scanf的返回值,以查看扫描数据是否成功。
  5. Add a length modifier to the second scanf to prevent buffer overflows: 在第二个scanf添加一个长度修饰符,以防止缓冲区溢出:

     scanf("%9s", name); /* +1 for the NUL-terminator */ 

You're not allocating space for name: 您没有为名称分配空间:

int b_insert(Book *b, int id, char *name){
    Book p; 
    p = malloc(sizeof(struct book));
    if (p != NULL)
    {
       p->name = malloc(strlen(name)+1); // It allocates space where the input name will be copied.

       if (p->name != NULL)
       {
          p->id = id;
          strcpy(p->name, name);

          *b = p;
          printf("success insert book:\n");
          printf("\tID: %d Name: %s\n", (*b)->id, (*b)->name);
       }
       else return -1; // No space to allocate string
    }
    else return -1; // No space to allocate struct

    return 0;
}

As mentioned before, allocate space for p->name . 如前所述,为p->name分配空间。 You should probably also use something different to read the book title, either scanf format %ms with a pointer to a char pointer, or %9s with your buffer, otherwise the title "war or peace" will also result in a segfault. 您可能还应该使用其他方式读取书名,或者将scanf格式的%ms带有指向char指针的指针,或者将%9s带有缓冲区,否则标题“ war or Peace”也将导致段错误。

Here you create a static variable and the space for it is allocated automatically. 在这里,您将创建一个静态变量,并为其自动分配空间。

Book p; 书p;

You can allocate a space manually when you assign it to pointer, in this line it's not pointer but static variable. 您可以在将空间分配给指针时手动分配空间,这行不是指针,而是静态变量。

p = (Book)malloc(sizeof(struct book)); p =(Book)malloc(sizeof(struct book));

What's more if you want to refer to attribute of static variable you should use "." 此外,如果要引用静态变量的属性,则应使用“。” instead of "->". 而不是“->”。 So you have two option. 因此,您有两种选择。 Create a pointer and allocate a space for the structure and then you "->" oraz create static variable. 创建一个指针并为该结构分配一个空间,然后“->” oraz创建静态变量。

p->id = id; p-> id = id;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM