小编phy*_*123的帖子

C中的内存分配错误

我已经在以下代码上工作了一段时间,当我尝试为结构及其元素分配/取消分配内存时出现了问题。感谢您对问题的任何见解。查看错误消息后,我认为问题出在以下事实:我试图释放一个我没有适当分配内存的元素,但是在查看代码时这对我来说并不明显。我还尝试了一些代码,在这些代码中我没有为结构的每个元素分别分配内存,但是效果并不理想。

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
 */ …
Run Code Online (Sandbox Code Playgroud)

c pointers dynamic-memory-allocation

5
推荐指数
1
解决办法
115
查看次数

标签 统计

c ×1

dynamic-memory-allocation ×1

pointers ×1