H_s*_*red 9 c memory malloc struct pointers
我今天很难修复代码,然后我遇到类似的东西:
typedef struct {
int a;
int b;
int c;
int d;
char* word;
} mystruct;
int main(int argc, char **argv){
mystruct* structptr = malloc(sizeof(mystruct));
if (structptr==NULL) {
printf("ERROR!")
...
}
...
free(structptr);
return 0;
}
Run Code Online (Sandbox Code Playgroud)
代码由于事实而给出了大量内存错误,这char* word是一个可变长度的字符串,而malloc没有为它分配足够的内存.实际上它只是20 Bytes为整体分配struct.有没有解决这个问题的方法,而不是char*像char word[50]什么?
Dev*_*lus 20
您只为结构本身分配内存.这包括指向char的指针,它在32位系统上只有4个字节,因为它是结构的一部分.它不包含未知长度的字符串的内存,因此如果您想要一个字符串,您还必须手动为其分配内存.如果您只是复制一个字符串,您可以使用strdup()它来分配和复制字符串.你仍然必须自己释放内存.
mystruct* structptr = malloc(sizeof(mystruct));
structptr->word = malloc(mystringlength+1);
....
free(structptr->word);
free(structptr);
Run Code Online (Sandbox Code Playgroud)
如果您不想自己为字符串分配内存,那么您唯一的选择是在结构中声明一个固定长度的数组.然后它将成为结构的一部分,sizeof(mystruct)并将包含它.如果这适用与否,取决于您的设计.