Serialize directory tree to send over TCP

I am sending a dirtree over TCP to a client application. Dir node is a structure that looks like this:

struct node {
      char *name;
      int count_subnodes;
      struct node **subnodes;

To serialize:

void serialize(void *buffer, struct node *n, int *c){
    int i;
    memcpy(buffer+(*c), n, sizeof(*n));
    for(i = 0; i < n->count_subnodes; i++){
        serialize(buffer, n->subnode[i], c);

What am I doing wrong? It segfaults when I call serialize recursively for subnodes. Also, would I need any sort of marker for delimitation so that I can reconstruct tree on client side?

Edit: c is to keep count of current position in buffer.

EDIT 2: Typo. It was sizeof(*n) not c. Sorry


  1. How do you know your buffer is big enough?

  2. sizeof(n) will give the the size of the pointer, not the struct; use sizeof(*n)

  3. Check that n->subnode[i] is not NULL

You are copying the struct n, and giving it the sizeof c, which is an int*. I think your problem is with this line:

memcpy(buffer+(*c), n, sizeof(c));

Also, you really don't want to serialize the struct itself. If you do, then you're sending over a pointer to the name, when you really want to send the name instead.

I think you need to serialize the name and also the sub-node count. Maybe something like:

int name_length = strlen(n->name + 1); /* +1 for null terminator. */
memcpy(buffer+(*c), n->name, name_length);
*c += name_length;
memcpy(buffer+(*c), &n->count_subnodes, sizeof(n->count_subnodes));
*c += sizeof(n->count_subnodes);

Do keep in mind that when serializing binary data for different systems, you may run into endianness issues.

Make sure you're allocating buffer to be large enough. Overrunning buffer could certainly segfault. It could also be in how you are initially calling serialize. You also need to be sure that your node tree is valid with no dangling pointers. And you must be passing a valid int* in for c.

You might want to post a minimal example of the calling code.

Need Your Help

Call ASP function from button in table

html asp-classic

I create a dynamic table in asp classic for each row there is a button, i need that this button will active some function..

Detect if a web request is the result of an <img src=""> tag html

If you have &lt;img src=""&gt; on your page, the image load will result in another web request to the page that was originally loaded. Is there a way (in ASP.NET) to detect that the web request wa...