簡體   English   中英

分段故障scanf'ing指向字符串的指針

[英]segmentation fault scanf'ing pointer to string

我正在開發一個程序,在鏈表中存儲client類型的變量。 但是我在scanfs上遇到了分段錯誤。 指針對我來說是新的,所以我認為name變量有問題。 服務由一個字母定義。

typedef struct{
    char* name;
    unsigned long number;
    char service;
}Client; 

struct node {
    Cliente value;
    struct node *next;
};
typedef struct node *LinkedListNode;



int main(){
    LinkedListNode head;
    Cliente aux,aux2;
    char command;
    head = malloc(sizeof(struct node));
    head->next=NULL;
    comando= getchar();
    while(1){ 
    switch(command){
        case('a'):
                scanf("%s",aux.name);
                scanf("%lu",&aux.number);
                scanf("%c",&aux.service);
                if(list_search_name(head,aux)==0){                      
                    if(list_search_number(head,aux)==0)                 
                        list_insert(head,aux);
                }   
                getchar();
        break;

命令中的if鏈只是檢查列表中是否已存在插入的名稱和編號,以便插入。

我有另一個問題是:從我被告知你應該為每個malloc()有一個free() ,否則一些內存會泄漏,但在這種情況下,整個程序需要head變量因為我在每個命令中使用它來存儲/搜索/獲取數據。 程序何時關閉我還應該釋放內存嗎?

您正在使用未定義的字符串指針,導致未定義的行為。

將聲明更改為:

typedef struct{
    char name[32];
    unsigned long number;
    char service;
}Client; 

和第一個scanf()

scanf("%31s", aux.name);

此外,您應該檢查scanf()的返回值,它是I / O,因此它可能會失敗。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM