【发布时间】:2017-04-30 11:10:26
【问题描述】:
所以这是我的问题,我创建了这个结构:
typedef struct foo *fooPtr;
struct foo {
foo2Ptr node;
foo3Ptr node;
char *Random;
};
fooNew(char* String) {
int StringLength;
StringLength = strlen(String) + 1;
Newfoo = (fooPtr *)malloc(sizeof(fooPtr));
Newfoo->Random = (char*)malloc(StringLength * sizeof(char));
strcpy(Newfoo->Random, String);
/*Rest of foo members initialized below....*/
}
fooChangeRandom(fooPtr Foo, String) {
int StringLength;
StringLength = strlen(String) + 1;
free(Foo->Random);
Foo->Random = (char*)malloc(StringLength * sizeof(char));
strcpy(Foo->Random, String);
}
但每当我尝试打印新字符串时,我都会得到随机字符。我记得 C 要求我释放我使用 malloc、calloc 或 realloc 分配的所有内容,那么当 fooNew 结束时 Random 如何改变?尝试调试并且在 free 时我得到 SIGTRAP 错误,在 free() 被使用的行上,但是这是我创建的唯一动态分配的对象,我之前没有使用过 free。那么 malloc 或 free 的语法有什么我遗漏或有什么问题吗?
【问题讨论】:
-
从哪里获得 SIGTRAP?您至少应该能够查明导致它的线路或功能。
-
当它到达免费功能时,sry 以为我提到了它,现在编辑
-
将
malloc(StringLength * sizeof(char)更改为malloc((StringLength+1) * sizeof(char)或只是malloc(StringLength+1)。您需要多一个字节来存储终止零字符。 -
其实是 pras 说的,但我仍然想知道错误是什么,我试过了,但由于这是一个作业,我不想把所有东西都准备好,所以我写了一些伪代码只是为了让问题更明显,不过我会编辑它,谢谢
-
所有
malloc返回值的转换只会伤害你