Segmentation fault while using malloc with char pointers

前端 未结 5 1163
独厮守ぢ
独厮守ぢ 2021-01-22 16:20

I am new to C and learning structs. I am trying to malloc a char pointer with size 30 but it is giving a segmentation fault(core dump). I searched it on the interne

相关标签:
5条回答
  • 2021-01-22 16:52

    As many people have pointed out, you need to allocate memory for that str struct, before writing the fields of it.

    The best way to do so in C is:

    p = malloc(sizeof *p);
    

    This has the following advantages:

    1. No cast, since no cast is needed in C and having a cast can hide actual errors.
    2. No duplication of type information, by using the sizeof operator to compute how much storage is needed for the value p points at.

    When you then allocate the string space, you can simplify it to:

    p->f = malloc(30); 
    

    Because:

    1. No cast, for the very same reason.
    2. C guarantees that sizeof (char) is always 1, so using it like you did adds nothing, 1 * 30 is always just 30.

    Last, you should always check the return value of malloc() before using it, since it can fail and return NULL.

    0 讨论(0)
  • 2021-01-22 16:55

    Check for NULL values in return of malloc() function.

    Also str *p; < is not initialised.

    initialize p as str *p = malloc(sizeof(str));

    0 讨论(0)
  • 2021-01-22 16:57

    The problem lies here.

    str *p;   ---> Problem Line 1<br>
    p->f = (char*)malloc(sizeof(char)*30); ----> Problem  Line2
    p->l = (char*)malloc(sizeof(char)*30);
    

    You have declared a pointer p of type str.
    Problem 1:
    You have not initialized this pointer to NULL. Thus, p can point to anything.
    Problem 2:
    Since p is an uninitialized pointer, p->f can point anywhere which is causing the segfault. Below is the correct way

    str *p = NULL;
    p = malloc(sizeof(str));
    // Check p for NULL
    memset(p, 0, sizeof(str));
    

    Now you have an initialized memory pointed by p. You are now free to use it as you want.

    0 讨论(0)
  • 2021-01-22 16:58

    Here's your problem:

    str *p;
    

    You've declared a pointer to an instance of str, but you haven't initialized it with a value. You either need to move this variable to the stack:

    str p;
    

    ...or malloc some memory for it first:

    str *p = (str*)malloc(sizeof(str));
    
    0 讨论(0)
  • 2021-01-22 17:09

    You never allocated space for the struct itself, only a pointer to it.

    Try something like:

    str *p = malloc(sizeof(str));
    
    0 讨论(0)
提交回复
热议问题