trinity
trinity

Reputation: 91

malloc in c, struct

I made a struct like this:

struct a{
  char *name;
  char *value;
  struct a *next;
};

when I malloc for memory at first time, it's ok, and I can set 'name' and 'value' a corresponding value. but when I malloc for the second time, errors come. And It's a cgi, just show me "500 Internal server error".

I changed the pointer 'name' and 'value' to array, everything works.

I thought maybe the complier doesn't know how much memory to assign.

And do you have some ideas with this? I will appreciate every answer!

Upvotes: 1

Views: 2692

Answers (2)

Keith Thompson
Keith Thompson

Reputation: 263177

struct a {
    char *name;
    char *value;
    struct a *next;
};

struct a *head = malloc(sizeof *head);

The above allocates space for a single struct a object, but it doesn't initialize any of hte three pointers contained in a struct a. In particular, if you want name and value to point to strings, you'll need to allocate space for those strings:

head->name = malloc(5);
strcpy(head->name, "Fred");
head->value = malloc(8);
strcpy(head->value, "abcdefg";

This is considerably oversimplified. 5 and 8 are "magic numbers"; you should specify the sizes in a way that will remain consistent if you change the initial values. And you should always check whether malloc() returns a null pointer (even if you just terminate the program with an error message).

If you don't initialize name and value to point to some chunk of allocated memory, you might still be able to initialize what they point to (e.g., by doing the strcpys above without the mallocs). More precisely, the system won't necessarily diagnose the error.

Finally, you'll need a call to free() corresponding to each malloc() call.

Note that this is largely a guess based on your description. If you can show us your actual code, we can help you better.

Upvotes: 3

Matt Lacey
Matt Lacey

Reputation: 8255

If you use malloc with sizeof(struct a) it's just going to assign enough space to store the pointers name and value. You want these to be char arrays, then it'll know how much space to set aside for each instance of a.

Upvotes: 2

Related Questions