phy*_*123 5 c pointers dynamic-memory-allocation
我已经在以下代码上工作了一段时间,当我尝试为结构及其元素分配/取消分配内存时出现了问题。感谢您对问题的任何见解。查看错误消息后,我认为问题出在以下事实:我试图释放一个我没有适当分配内存的元素,但是在查看代码时这对我来说并不明显。我还尝试了一些代码,在这些代码中我没有为结构的每个元素分别分配内存,但是效果并不理想。
typedef struct {
char *cnet;
char *email;
char *fname;
char *lname;
char *tel;
} vcard;
vcard *vcard_new(char *cnet, char *email, char *fname, char *lname, char *tel)
{
vcard* new = (vcard*)malloc(sizeof(vcard));
printf("%lu\n", sizeof(new->tel) );
new->cnet = malloc(sizeof(new->cnet));
new->email = malloc(sizeof(new->email));
new->fname = malloc(sizeof(new->fname));
new->lname = malloc(sizeof(new->lname));
new->tel = malloc(sizeof(new->tel));
new->cnet = cnet;
new->email = email;
new->fname = fname;
new->lname = lname;
new->tel = tel;
return new;
}
/* vcard_free : free vcard and the strings it points to
*/
void vcard_free(vcard *c)
{
free(c->cnet);
free(c->email);
free(c->fname);
free(c->lname);
free(c->tel);
free(c);
return;
}
Run Code Online (Sandbox Code Playgroud)
您的整个内存分配是错误的。这里有一些指针。
您只为一个分配内存char *,这不是预期的。
然后,通过将参数分配给将指针分配给已分配内存的相同变量来覆盖已分配内存。
malloc()and家庭返回的。
free(),导致未定义的行为printf()
sizeof产生类型为的结果size_t,您必须使用它%zu来打印结果。解决方案:
分配足够的内存来存储预期的内容,例如预定义的大小
#define CNETSIZ 32
#define EMAILSIZ 64
. . . . .
new->cnet = malloc(CNETSIZ);
new->email = malloc(EMAILSIZ);
Run Code Online (Sandbox Code Playgroud)
或者,根据输入字符串的长度,例如
new->cnet = malloc(strlen(cnet)+1); //+1 for the space to null-terminator
Run Code Online (Sandbox Code Playgroud)在vcard_new()函数内部,用于strcpy()从函数参数中复制内容,例如
strcpy(new->cnet, cnet);
strcpy(new->email, email);
Run Code Online (Sandbox Code Playgroud)