C 使用指针的结构出错
我为构建器bob编写了代码,它是一个结构,构建器中的每个bob都有名称和两个以上的整数并不重要。有三个功能 使用bob、0和3初始化结构 第二个函数得到两个结构,它需要在这些结构之间进行复制 第三个功能是释放每个bob的nameschar* 首先,第二个functioncopy在调试中出错,因为它没有复制名称,需要您帮助分析为什么会发生这种情况;其次,代码在自由函数中崩溃。有人能告诉我如何释放nameschar*的结构吗C 使用指针的结构出错,c,pointers,struct,malloc,dynamic-memory-allocation,C,Pointers,Struct,Malloc,Dynamic Memory Allocation,我为构建器bob编写了代码,它是一个结构,构建器中的每个bob都有名称和两个以上的整数并不重要。有三个功能 使用bob、0和3初始化结构 第二个函数得到两个结构,它需要在这些结构之间进行复制 第三个功能是释放每个bob的nameschar* 首先,第二个functioncopy在调试中出错,因为它没有复制名称,需要您帮助分析为什么会发生这种情况;其次,代码在自由函数中崩溃。有人能告诉我如何释放nameschar*的结构吗 #include <stdio.h> #include <
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#define LENGTH_OF_BOB 4
typedef struct bobTheBuilder
{
char* name;
int fixed;
int maxFix;
}bob;
//typedef struct bobTHeBuilder bob;
void deleteBob(bob currBob);
void initBob(bob *currBob);
void copyStruct(bob* dst, bob src);
int main(void)
{
bob currBob = {0,0,0};
bob secondBob;
initBob(&currBob);
copyStruct(&secondBob, currBob);
deleteBob(currBob);
deleteBob(secondBob);
system("PAUSE");
return 0;
}
/*
*/
void initBob(bob *currBob)
{
char* str = (char*)calloc(LENGTH_OF_BOB, sizeof(char));
char string[] = "bob";
if (str)
{
strcat(string, "\0");
str = string;
currBob->name = str;
currBob->fixed = 0;
currBob->maxFix = 3;
}
}
/*
*/
void deleteBob(bob currBob)
{
free(currBob.name);
}
void copyStruct(bob* dest, bob src)
{
dest->fixed = src.fixed;
dest->maxFix = src.maxFix;
dest->name = (char*)malloc(sizeof(char) *LENGTH_OF_BOB);
strncpy(dest->name, src.name, LENGTH_OF_BOB);
}
在initBob中,您有:
char* str = (char*)calloc(LENGTH_OF_BOB, sizeof(char));
char string[] = "bob";
str = string;
currBob->name = str;
将currBob->name设置为指向本地自动变量。而不是动态分配的缓冲区。当函数退出时,自动变量超出范围,因此不再有效。当然,它不能被释放,因为它不是动态分配的内存
我真的不确定你在那里想做什么。除了错误地将str设置为指向局部变量外,还存在不必要的strcat。我猜您正在尝试NUL终止缓冲区。但这是不必要的,因为用字符串文本初始化未指定大小的字符数组已经保证了NUL终止
考虑到这些问题,initBob函数应该更像:
void initBob(bob *currBob)
{
currBob->name = calloc(LENGTH_OF_BOB, sizeof(char));
if (currBob->name)
{
strcpy(currBob->name, "bob");
currBob->fixed = 0;
currBob->maxFix = 3;
}
}
我不知道这是否只是一个简单的例子来学习如何做,或者它是否真的是您的范围,但如果您需要这样做,请使用:strdup
void initBob(bob *currBob)
{
if (currBob->name)
{
currBob->name=strdup("bob");
currBob->fixed = 0;
currBob->maxFix = 3;
}
}
你必须在某个地方释放它,因为malloc字符串。。。它是ANSI标准的。当你认为它不会变得更糟时,strncpy真的会踢你的内脏。谷歌为什么strncpy不安全。