Allocate memory for a structure with a pointer to a character in C

I struggled to fix the 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 returned a lot of memory errors due to the fact that char* word is a string of variable length, and malloc does not allocate enough memory for this. In fact, it was just 20 Bytes allocation for the whole struct . Is there a way around this problem without turning char* into sth like char word[50] ?

+7
c pointers struct malloc memory
source share
6 answers

You only allocate memory for the structure itself. This includes a pointer to char, which is only 4 bytes on a 32-bit system, since it is part of the structure. It does NOT include memory for an unknown string length, so if you want to have a string, you must also manually allocate memory for it. If you just copy the string, you can use strdup() , which selects and copies the string. You still have to free your memory.

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

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

+16
source share

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

 mystruct* structptr = malloc(sizeof(mystruct)); structptr->word = malloc(sizeof(WhatSizeYouWant)); 
+4
source share

Add a second malloc for any length (N) needed for word

  mystruct* structptr = malloc(sizeof(mystruct)); structptr->word = malloc(sizeof(char) * N); 
+3
source share

When you allocate memory for structptr , the word pointer in the struct does not have a valid memory to indicate. That way, you either malloc piece of memory for word too, or make word points to another character.

+1
source share

malloc, the external structure will allocate only 1 byte memory specified by *word , since this is of type 'char *'. If you want to allocate more than 1 byte of memory that word points to, there are 2 options:

  • As you said, declare it as char word[50] instead of `char * '
  • malloc / calloc (I personally prefer calloc, saving you the zeromemory problem, which is very important ..) the external structure, then malloc / calloc is the internal word . Remember to also call free in this case.
0
source share

Use word=malloc(128);

this will allocate 128 bytes to your variable word,

-one
source share

All Articles