Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/c/55.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C 分段故障扫描';正在删除指向字符串的指针_C_Gcc_Segmentation Fault - Fatal编程技术网

C 分段故障扫描';正在删除指向字符串的指针

C 分段故障扫描';正在删除指向字符串的指针,c,gcc,segmentation-fault,C,Gcc,Segmentation Fault,我正在开发一个程序,将client类型的变量存储在一个链表中。然而,我在扫描上发现了一个分割错误。指针对我来说是新的,所以我假设name变量有问题。服务由一个字母定义 typedef struct{ char* name; unsigned long number; char service; }Client; struct node { Cliente value; struct node *next; }; typedef struct node

我正在开发一个程序,将client类型的变量存储在一个链表中。然而,我在扫描上发现了一个分割错误。指针对我来说是新的,所以我假设
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,因此可能会失败。

每个malloc()一个free()的经验法则的原因是为了防止内存泄漏(请参阅本文以及上的这篇文章)。对于大多数操作系统上的现代运行时库,当程序终止时,所有分配的内存将返回到操作系统。然而,将free()与malloc()匹配是一个需要培养的好习惯。