Allocate memory for a struct with a character poin

2020-05-19 07:55发布

I was struggling to fix a code today, then I come across something similar to:

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;
}

the code was giving lots of memory errors due to the fact, that char* word is a string of variable length, and malloc was not allocating enough memory for it. In fact it was only allocating 20 Bytes for the whole struct. Is there a way around this issue, without turning the char* into sth like char word[50]?

6条回答
Animai°情兽
2楼-- · 2020-05-19 08:32

You are allocating only memory for the structure itself. This includes the pointer to char, which is only 4 bytes on 32bit system, because it is part of the structure. It does NOT include memory for an unknown length of string, so if you want to have a string, you must manually allocate memory for that as well. If you are just copying a string, you can use strdup() which allocates and copies the string. You must still free the memory yourself though.

 mystruct* structptr = malloc(sizeof(mystruct));
 structptr->word = malloc(mystringlength+1);

 ....

 free(structptr->word);
 free(structptr);

If you don't want to allocate memory for the string yourself, your only choice is to declare a fixed length array in your struct. Then it will be part of the structure, and sizeof(mystruct) will include it. If this is applicable or not, depends on your design though.

查看更多
▲ chillily
3楼-- · 2020-05-19 08:33

malloc the outer struct will only allocate 1 byte memory pointed by *word since it is a 'char *' type. If you want to allocate more than 1 byte of memory pointed by word, there are 2 options:

  1. Like what you said, declare it as char word[50] instead of `char *'
  2. malloc/calloc (I personally prefer calloc, saving you the trouble of zeromemory, which is a very important..) the outer struct, then malloc/calloc the inner word as well. Remember to call free twice as well in this case.
查看更多
三岁会撩人
4楼-- · 2020-05-19 08:36

Add a second malloc for whatever length (N) you need for word

   mystruct* structptr = malloc(sizeof(mystruct));

   structptr->word = malloc(sizeof(char) * N);
查看更多
祖国的老花朵
5楼-- · 2020-05-19 08:42

Use word=malloc(128);

this will allocate 128 bytes to your varible word,

查看更多
欢心
6楼-- · 2020-05-19 08:47

When you allocate memory for structptr, the pointer word in the struct has no valid memory to point. So you either malloc a piece of memory for word, too, or make word point to another character.

查看更多
聊天终结者
7楼-- · 2020-05-19 08:57

as you can read here you need to allocate the char * separately :

mystruct* structptr = malloc(sizeof(mystruct));
structptr->word = malloc(sizeof(WhatSizeYouWant));
查看更多
登录 后发表回答