Segmentation fault while using malloc with char pointers

前端 未结 5 1168
独厮守ぢ
独厮守ぢ 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:57

    The problem lies here.

    str *p;   ---> Problem Line 1
    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.

提交回复
热议问题