Passing string variable by reference

Viewed 71

I've this piece of code :

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

void b(char *in, char ** out);

int main()
{
    char a[] = {'w','o','r','l','d','\0'};
    char *d = nullptr;
    b(a, &d);
    printf("hello %s\n", d);
    return 0;
}

void b(char *in, char ** out)
{
    char tmp[10];
    for(int i=0;i<6;i++)
        tmp[i]=in[i];

    *out=tmp;

    printf("%s\n", *out);
}

I except to get theses printf :

world
hello world

But I get these :

world
hello

Why the d variable isn't fullfilled ? :(

Thanks for any clue about that !

1 Answers

Inside of b(), you are setting the char* referred by out to point at a local char[] array, which is NOT being null-terminated (thus breaking "%s" in printf()), but also WILL go out of scope when b() exits, thus the caller (ie main()) ends up with a dangling char* pointer to invalid memory.

You tagged your question as . C++ is not C. You should use std::string instead of char[] in this situation, eg:

#include <iostream>
#include <string>

void b(const std::string &in, std::string &out);

int main()
{
    std::string a = "world";
    std::string d;
    b(a, d);
    std::cout << "hello " << d << "\n";
    return 0;
}

void b(const std::string &in, std::string &out)
{
    std::string tmp = in.substr(0, 6);
    out = tmp;
    std::cout << out << "\n";
}

Otherwise, if you really want to use char*, in C or C++, you will need to use dynamic memory allocation, eg:

#include <stdio.h>  // or <cstdio> in C++
#include <string.h> // or <cstring> in C++

void b(char *in, char ** out);

int main()
{
    char a[] = "world";
    char *d = nullptr;
    b(a, &d);
    printf("hello %s\n", d);
    delete[] d; // or free() in C
    return 0;
}

void b(char *in, char ** out)
{
    char *tmp = new char[7]; // or malloc() in C
    for(int i = 0; i < 6; ++i) {
        tmp[i] = in[i];
    }
    tmp[6] = '\0';

    *out = tmp;

    printf("%s\n", *out);
}
Related