【发布时间】:2021-09-18 23:42:10
【问题描述】:
我有一些简单的代码可以创建一个新结构(包含一个字符串和一个长度),然后删除该结构。
/* 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 文件中删除 this 行时:
S ->len = length;
...两个测试都通过了!
为什么程序运行良好,通过了测试,但是当我尝试对范围内的结构进行更改时,它会导致我的代码中看似不相关的部分出现段错误?
我没有看到这些是什么关系...你能帮帮我吗?
【问题讨论】:
-
你试过使用 valgrind 吗?
-
typedef struct string* String;只会导致悲伤。 -
不,我没有尝试过使用 valgrind——我不熟悉这个工具,但我会试一试。是的,我很难过。
标签: c string struct segmentation-fault free