Variadic Template causes double free

  c++, c++17, templates

I was trying to write a simple function to concatenate pairs of strings from a variadic template (just to try to mess with variadic templates)

Expected Input and Output

{Hello, 1}, {Hello, D}


BaseRecoveryHello=1Hello=D

This is what I came up with

#include <stdio.h>
#include <utility> 
#include <string>
#include <iostream>

template<typename T, typename... Args>
std::string log_kv_rec(std::string& current, std::pair<std::string, T>& a, std::pair<std::string, Args>&... args) {
  current += a.first + "=" + std::to_string(a.second); 
}

template<typename... Args>
std::string log_kv(const std::string& a, std::pair<std::string, Args>&... args) {
    int i = 0;
    
    std::string current = a;
    log_kv_rec( current, args...);
    return current;
}

int main()
{   
    auto p1 = std::pair<std::string, int>{"Hello", 1};
    auto p2 = std::pair<std::string, std::string>{"Hello", "D"};
    std::cout << log_kv("BaseRecovery", p1, p2) << std::endl;

    return 0;
}

However, when I run it, the compiler gives me a double free or memory corruption errror

https://onlinegdb.com/6vAcN0G5w

Could someone explain why this causes a double free? Also, please tell me if anything in this is inherently a bad idea.

Source: Windows Questions C++

LEAVE A COMMENT