2

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 !

5
  • You did not allocated memory for d. Commented Jan 13, 2021 at 19:10
  • Filled with what? The contents of a dead local variable? Look up "dangling pointer" and consider using actual [std::] string variables... ;) Commented Jan 13, 2021 at 19:10
  • @Eraklon If they had, they would have leaked it. Commented Jan 13, 2021 at 19:10
  • 1
    @Eraklon That is not a problem because they never dereference **out. Commented Jan 13, 2021 at 19:11
  • There is no reference in your code (no string either), what do you mean in subject? Commented Jan 13, 2021 at 19:13

1 Answer 1

6

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);
}
Sign up to request clarification or add additional context in comments.

1 Comment

Sorry for the bad tag, and thanks for the second solution : i understand now the mistake :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.