首页 > 解决方案 > 释放时填充结构数据会导致段错误

问题描述

我有一些简单的代码可以创建一个新结构(包含一个字符串和一个长度),然后删除该结构。

/* string/proc.c */

#include "proc.h" /* String */
#include <malloc.h>
#include <assert.h>
#include <stddef.h> /* NULL */

struct string {
        char* str;
        int   len;
};


String new_string (int length)
{
        String S;
        S = (String) malloc (sizeof (String));
        S ->str = (char*) malloc (sizeof (char*) * length + 1);
        S ->str [length] = '\0';
        S ->len = length;

        return S;
}


void delete_string (String *Sp)
{
        free ((*Sp) ->str);
        free (*Sp);
        *Sp = NULL;
}

/* end of file */

这些函数通过头文件公开,并且结构是 typedef 的。

/* string/proc.h */
#ifndef string_proc_h
#define string_proc_h

typedef struct string* String;

String new_string (int length);
void delete_string (String*);

#endif
/* end of file */

我还有一个测试文件,其中#include 是那个头文件并测试新功能和删除功能:

/* string/proc_test.c */

#include "proc.h"
#include <assert.h>
#include <stddef.h> /* NULL */

int test_new_string ()
{
        int ok = 0;

        String S = new_string (10);
        assert (S);
        ok ++;

        delete_string (&S);

        return ok;
}


int test_delete_string ()
{
        int ok = 0;

        String S = new_string (10);
        delete_string (&S);
        assert (S == NULL);
        ok ++;

        return ok;
}

/* end of file */

问题:当我运行这个程序时,我得到一个分段错误(核心转储)。

我可以在这一行使用 dbg 将其跟踪到 proc.c 文件:

*Sp = NULL;

然而:

当我从 proc.c 文件中删除这一行时:

S ->len = length;

...两个测试都完美通过!

为什么程序运行得很好,通过了测试,但是当我尝试对范围内的结构进行更改时,它会导致我的代码中看似不相关的部分出现段错误?

我没有看到这些是如何相关的......你能帮我吗?

标签: cstringstructsegmentation-faultfree

解决方案


线条

        S = (String) malloc (sizeof (String));
        S ->str = (char*) malloc (sizeof (char*) * length + 1);

错了。它应该是:

        S = malloc (sizeof (*S));
        S ->str = malloc (sizeof (*(S->str)) * length + 1);

或者

        S = malloc (sizeof (struct string));
        S ->str = malloc (sizeof (char) * length + 1);

第一行是致命的。它只分配一个指针,而需要分配结构。第二行不是致命的,但它会分配一些额外的内存,因为它为每个元素分配一个指针,而只需要一个字符的空间。

另请注意,malloc()家庭的铸造结果被认为是一种不好的做法

另一个建议是你不应该typedef像这样隐藏指针,因为它会使它更加混乱。


推荐阅读