Here are my structures (defined in a header file):
typedef struct
{
char *name;
char *value;
} struct_param;
typedef struct
{
char *UID;
int number;
char *type;
char *name;
struct_param param[10];
} struct_cmd;
the prototype :
struct_cmd *ParseFile(char buffer[]);
The function in the c file:
struct_cmd *ParseFile(char buffer[])
{
struct_cmd *cmd;
cmd = malloc(sizeof(struct_cmd));
...
if (mxmlGetFirstChild(node_msgUID) != NULL)
cmd->UID = node_msgUID->child->value.opaque;
...
printf("Message Type :: %s | Message UID :: %s \n", cmd->type, cmd->UID);
...
return cmd;
}
The printf in ParseFile works perfectly.
Now, from the main function:
int main(int argc, char **argv)
{
...
struct_cmd *mystruct;
mystruct = malloc(sizeof(struct_cmd));
mystruct = ParseFile(buf);
printf("Message Type :: %s | Message UID :: %s \n", mystruct->type, mystruct->UID);
...
}
The same printf doesn't work. The function returns the structure, but values are weird... It's not values, but strange characters.
Any idea? Thanks
You are making a shallow copy from the data allocated by Mini-XML to your own struct cmd.
For example, this statement copies a pointer, not the actual characters:
cmd->UID = node_msgUID->child->value.opaque;
cmd->UID still refers to the original memory block allocated by Mini-XML. There's nothing wrong with that, just remember that this memory will be de-allocated once you call mxmlDelete. Which is probably what you are doing somewhere near the end of function ParseFile. I am guessing here, since you did not post all your code.
Possible solutions:
cmd->UID = strdup(node_msgUID->child->value.opaque);Remember, you are programming in plain C, without a garbage collector. Memory management is your responsibility.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With