Working with C-Style Strings

Efficient C-String Concatenation

What's the most memory-efficient way to concatenate multiple C-style strings?

Abstract art representing computer programming

Concatenating multiple C-style strings efficiently requires careful memory management. The most memory-efficient approach involves calculating the total length needed, allocating memory once, and then copying the strings into the new buffer. Here's a step-by-step implementation:

  1. Calculate the total length needed.
  2. Allocate memory for the result.
  3. Copy each string into the result buffer.
  4. Null-terminate the result.

Here's an example implementation:

#include <iostream>
#include <cstring>
#include <memory>
#include <vector>

char* concatenateStrings(
  const std::vector<const char*>& strings
) {
  // Calculate total length
  // Start with 1 for null terminator
  size_t totalLength{1};  
  for (const auto& str : strings) {
    totalLength += std::strlen(str);
  }

  // Allocate memory
  char* result{new char[totalLength]};

  // Copy strings
  char* ptr{result};
  for (const auto& str : strings) {
    size_t len{std::strlen(str)};
    std::memcpy(ptr, str, len);
    ptr += len;
  }

  // Null-terminate
  *ptr = '\0';

  return result;
}

int main() {
  std::vector<const char*> strings{
    "Hello", ", ",   "World",  "! ", 
    "How ", "are ",  "you",   "?"
  };

  char* concatenated{concatenateStrings(strings)};

  std::cout << "Concatenated string: "
    << concatenated << '\n';

  // Don't forget to free the memory!
  delete[] concatenated;
}
Concatenated string: Hello, World! How are you?

This approach is memory-efficient because:

  1. We allocate memory only once, based on the exact size needed.
  2. We avoid multiple reallocations that would occur if we used strcat() in a loop.
  3. We use memcpy() for copying, which is generally faster than strcpy() for larger strings.

However, this method requires manual memory management, which can be error-prone. We can improve on this using smart pointers:

#include <iostream>
#include <cstring>
#include <memory>
#include <vector>

std::unique_ptr<char[]> concatenateStrings(
    const std::vector<const char*>& strings) {
  size_t totalLength{1};
  for (const auto& str : strings) {
    totalLength += std::strlen(str);
  }

  auto result{std::make_unique<char[]>(
    totalLength)};

  char* ptr{result.get()};
  for (const auto& str : strings) {
    size_t len{std::strlen(str)};
    std::memcpy(ptr, str, len);
    ptr += len;
  }

  *ptr = '\0';

  return result;
}

int main() {
  std::vector<const char*> strings{
    "Hello", ", ",   "World",  "! ",
    "How ", "are ", "you",   "?"};

  auto concatenated{concatenateStrings(strings)};

  std::cout << "Concatenated string: "
    << concatenated.get() << '\n';
}
Concatenated string: Hello, World! How are you?

This version uses std::unique_ptr to manage the memory, eliminating the need for manual delete.

While these methods are efficient for C-style strings, it's worth noting that in modern C++, using std::string is often more convenient and safer:

#include <iostream>
#include <string>
#include <vector>

std::string concatenateStrings(
    const std::vector<std::string>& strings) {
  std::string result;
  for (const auto& str : strings) {
    result += str;
  }
  return result;
}

int main() {
  std::vector<std::string> strings{
    "Hello", ", ", "World", "! ",
    "How ", "are ", "you",   "?"};

  std::string concatenated{
    concatenateStrings(strings)};

  std::cout << "Concatenated string: "
    << concatenated << '\n';
}
Concatenated string: Hello, World! How are you?

This std::string version is not only safer but can also be more efficient in many cases, as std::string can preallocate memory and grow dynamically as needed.

Answers to questions are automatically generated and may not have been reviewed.

A computer programmer
Part of the course:

Professional C++

Comprehensive course covering advanced concepts, and how to use them on large-scale projects.

Free, unlimited access

This course includes:

  • 124 Lessons
  • 550+ Code Samples
  • 96% Positive Reviews
  • Regularly Updated
  • Help and FAQ
Free, Unlimited Access

Professional C++

Comprehensive course covering advanced concepts, and how to use them on large-scale projects.

Screenshot from Warhammer: Total War
Screenshot from Tomb Raider
Screenshot from Jedi: Fallen Order
Contact|Privacy Policy|Terms of Use
Copyright © 2024 - All Rights Reserved