-2

I have following structure:

typedef struct
{
    char *name[10];
    char *msg[100];
} Log;

How I can free the name and msg arrays from Log structure? I know free is used only for dynamic allocation, and dynamic allocation doesn't work in structures. What I can do?

Tryed this but give error:

typedef struct
{
    char *name[] = (char *)malloc(sizeof(char) * 10);
    char *msg[] = (char *)malloc(sizeof(char) * 100);
} Log;

Who can help me? Thanks!

braX
  • 11,506
  • 5
  • 20
  • 33
Mihail Feraru
  • 175
  • 1
  • 3
  • 14
  • 1
    You have tagged this as C++, but the code is most certainly C. Which do you want an answer in? – TartanLlama Sep 10 '14 at 13:54
  • 2
    Depends. First off, a `char* x[]` is a char-ptr array. `char *name[10]` allocates 10 char ptrs, which is not what you want to do. `typedef struct {char name[10]; char msg[100];} Log;` will allocate these fields as inline to the structure (`sizeof(Log)>=110`). Else you'll need to provide an init and cleanup function for the struct. Personally, in such cases I make the user only interact with handles and never the struct directly. – IdeaHat Sep 10 '14 at 14:01
  • 1
    `sizeof(char)` is per definitionem 1, so don't write it. Also, [Don't cast the result of malloc (and friends)](http://stackoverflow.com/q/605845). – Deduplicator Sep 10 '14 at 14:06

1 Answers1

3

Declaring a structure doesn't allocate memory for its members. Memory is allocated when an instance of a structure is created. So

typedef struct
{
    char *name[10];
    char *msg[100];
} Log;  

doesn't allocate memory for name and msg, it just declare Log as a new data (user defined) type. But when you create an instance of it

Log log_flie;

memory is allocated for name and msg. Now you can allocate memory (dynamically) for elements of data member as

for(int i = 0; i < 10; i++)
    log_file.name[i] = malloc(N);  //N is the desired size  

Similarly you can do for msg.

To free the dynamically allocated memory, call free as

for(int i = 0; i < 10; i++)
    free(log_file.name[i]);    

If you want to allocate memory for name and msg dynamically then do as follows

typedef struct
{
    char **name;
    char **msg;
} Log;  

Then

Log log_file;
log_file.name = malloc(10 * sizeof(char *));
log_file.msg = malloc(100 * sizeof(char *));  
haccks
  • 104,019
  • 25
  • 176
  • 264