【问题标题】:segmentation fault scanf'ing pointer to string分段错误扫描指向字符串的指针
【发布时间】:2013-12-04 12:44:05
【问题描述】:

我正在开发一个程序,它将客户端类型的变量存储在一个链表中。但是我在 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 变量是在整个程序中都需要它,因为我在每个命令中都使用它来存储/搜索/获取数据。当程序关闭时,我还应该释放内存吗?

【问题讨论】:

  • 每个 malloc() 一个 free() 的经验法则是为了防止内存泄漏(请参阅此 wikipedia memory leaks article 以及有关 pointers and memory leaks in C 的这篇文章)。对于大多数操作系统上的现代运行时库,当程序终止时,所有分配的内存都会返回给操作系统。但是将 free() 与 malloc() 匹配是一个好习惯。

标签: c gcc segmentation-fault


【解决方案1】:

您正在使用未定义的字符串指针,导致未定义的行为。

将声明更改为:

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

和第一个scanf()

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

另外,你应该检查scanf()的返回值,它是I/O所以它可能会失败。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-10-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多