C#
list conversion
strings
programming
C# tutorial

Convert a list to a string in C

Master System Design with Codemia

Enhance your system design skills with over 120 practice problems, detailed solutions, and hands-on exercises.

Introduction

In C, converting a linked list to a string is mostly a memory-management problem. The safe approach is to decide on the output format first, calculate the required buffer size, allocate once, and then write into that buffer with bounded formatting logic.

Define the Output Format Up Front

Before writing code, decide what “convert the list to a string” means. A list of integers might become:

  • '"1,2,3"'
  • '"[1, 2, 3]"'
  • one value per line

That choice affects both the size calculation and the write logic.

For a simple singly linked list of integers, the structure might look like this:

c
1typedef struct Node {
2    int value;
3    struct Node *next;
4} Node;

The rest of the problem is formatting and ownership.

Use a Two-Pass Strategy

The simplest reliable pattern in C is:

  1. walk the list once and compute the exact length needed
  2. allocate one heap buffer
  3. walk the list again and write the formatted output

This avoids guessing at buffer sizes and avoids repeated reallocation.

c
1#include <stdio.h>
2#include <stdlib.h>
3
4char *list_to_string(const Node *head) {
5    size_t len = 3; /* '[', ']', '\0' */
6    const Node *cur;
7
8    for (cur = head; cur != NULL; cur = cur->next) {
9        len += snprintf(NULL, 0, "%d", cur->value);
10        if (cur->next != NULL) {
11            len += 2; /* ", " */
12        }
13    }
14
15    char *out = malloc(len);
16    if (out == NULL) {
17        return NULL;
18    }
19
20    char *p = out;
21    *p++ = '[';
22
23    for (cur = head; cur != NULL; cur = cur->next) {
24        int written = sprintf(p, "%d", cur->value);
25        p += written;
26        if (cur->next != NULL) {
27            *p++ = ',';
28            *p++ = ' ';
29        }
30    }
31
32    *p++ = ']';
33    *p = '\0';
34    return out;
35}

This produces one allocation and one final contiguous string.

Make the Example Runnable

A conversion function is easier to trust when the ownership rules are visible in a complete example.

c
1#include <stdio.h>
2#include <stdlib.h>
3
4int main(void) {
5    Node c = {30, NULL};
6    Node b = {20, &c};
7    Node a = {10, &b};
8
9    char *text = list_to_string(&a);
10    if (text == NULL) {
11        fprintf(stderr, "allocation failed\n");
12        return 1;
13    }
14
15    printf("%s\n", text);
16    free(text);
17    return 0;
18}

Output:

text
[10, 20, 30]

For an empty list, the same function returns [], which is a reasonable default in many programs.

Why Repeated strcat Is a Bad Default

A beginner implementation often starts with a fixed-size buffer and repeated strcat. That works on tiny inputs, but it repeatedly scans the current string to find the end, which makes the total work grow unnecessarily as the list gets longer.

It also makes buffer accounting harder, because you must constantly ensure there is enough remaining space before each concatenation.

Pointer-based writing is simpler once you know the total length.

If You Cannot Know the Final Size

There are cases where the final size is not easy to know ahead of time. In that situation, a realloc-based growth strategy is reasonable. But for a normal list-to-string helper, the two-pass approach is usually easier to read, easier to verify, and less error-prone.

That is why it is the default recommendation.

Be Explicit About Ownership

The function returns heap memory, so the caller owns the result and must call free. In C, many string-conversion bugs are really ownership bugs:

  • returning a pointer to stack memory
  • leaking the heap buffer
  • freeing the result too early

The best way to avoid confusion is to document the contract clearly: the function allocates and returns a new string, and the caller releases it.

Common Pitfalls

  • Allocating a fixed-size buffer and assuming it is always large enough.
  • Building the result with repeated strcat calls.
  • Forgetting space for separators, brackets, minus signs, or the null terminator.
  • Returning a pointer to temporary storage instead of heap memory.
  • Failing to document that the caller must free the returned string.

Summary

  • In C, converting a list to a string is mainly a buffer-sizing and ownership problem.
  • A two-pass approach is the clearest safe solution: measure first, allocate once, then write.
  • 'snprintf(NULL, 0, ...) is useful for exact length calculation.'
  • Direct writes into the output buffer are better than repeated concatenation.
  • Make the ownership contract explicit so the returned string is freed correctly.

Course illustration
Course illustration

All Rights Reserved.