Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Strange characters from char array in structure

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

like image 769
10h02 Avatar asked Jun 18 '26 10:06

10h02


1 Answers

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:

  1. Instead of a shallow copy, make a deep copy, e.g. with strdup: cmd->UID = strdup(node_msgUID->child->value.opaque);
  2. Do all processing before freeing memory.

Remember, you are programming in plain C, without a garbage collector. Memory management is your responsibility.

like image 119
Ruud Helderman Avatar answered Jun 20 '26 23:06

Ruud Helderman



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!