C结构:初始化有问题吗? Valgrind错误

| 用C编码:
typedef struct {
   char *string;
   int one;
   int two;
} Example;
...其他地方:
Example *new = (Example *)malloc(sizeof(Example*));
new->string = strdup(otherstring); //no problem here
new->one = 5; //valgrind says that there is an invalid write of size 4.
我的程序运行良好,只是让valgrind不高兴。这可能意味着我将在其他地方出现其他错误。 我猜我不必声明指向该结构的指针(即,我可以调用\“ example new \”),但是我一直在寻找如何在堆上分配内存的方法,因为我需要从程序的其他部分访问“新”。 我在以上几行中犯了一个错误吗?还是我的错误可能在其他地方?这是valgrind报告的第一个内存错误。 编辑:在我的结构中意外有int * s而不是int。固定。
已邀请:
我在这里看到各种问题。首先,这是:
Example *new = (Example *)malloc(sizeof(Example*));
不会分配适当的内存量(并且您不需要强制转换)。你要这个:
Example *new = malloc(sizeof(Example));
然后,你这样说:
new->one = 5;
并且将ѭ5分配给
int*
;这不是一个好主意,而valgrind正确地对此抱怨。如果正确地声明了您的“ 7”,那么您需要这样做:
new->one = malloc(sizeof(int)); /* The other malloc doesn\'t allocate this, you have to. */
*(new->one) = 5;
我怀疑(正如您所说的,一切正常)您真的要这样声明您的
struct
typedef struct {
   char *string;
   int one;
   int *two;
} Example;
但是没有足够的信息来确定。那么您可能仍然对ѭ11有类似的问题。
范例* new =(范例)malloc(sizeof(范例)); 应该: 示例* new =(示例*)malloc(sizeof(Example); 您必须分配整个结构,而不仅仅是对其的引用。有时程序运行只是因为您很幸运。
请尝试以下操作(只需剪切,粘贴并运行):
Example *new = (Example *)malloc(sizeof(Example));  //This is the correct method as pointed out by Bob, otherwise you\'re allocating only enough space to fit a memory location vs the struct
new->string = strdup(otherstring);  //this is okay
new->one = (int*)malloc(sizeof(int));
*(new->one) = 5; //You want to assign the value 5 to the new->one memory location, not assign new->one pointer the value of 5!!!

要回复问题请先登录注册