0

I am confused with const pointers in C++ and wrote a small application to see what the output would be. I am attempting (I believe) to add a pointer to a string, which should not work correctly, but when I run the program I correctly get "hello world". Can anyone help me figure out what how this line (s += s2) is working?

My code:

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

using namespace std;

const char* append(const char* s1, const char* s2){
    std::string s(s1);     //this will copy the characters in s1
    s += s2;               //add s and s2, store the result in s (shouldn't work?)
    return s.c_str();      //return result to be printed
}

int main() {
    const char* total = append("hello", "world");
    printf("%s", total);
    return 0;
}
Drew McGowen
  • 11,471
  • 1
  • 31
  • 57
user1615559
  • 333
  • 2
  • 8
  • 18
  • `stdio.h` is deprecated in C++. Use `cstdio`. Anyway, you have [undefined behaviour](http://stackoverflow.com/questions/6441218/can-a-local-variables-memory-be-accessed-outside-its-scope). – chris Jul 30 '14 at 18:51
  • 1
    You're effectively returning a pointer/reference to a local variable, which is undefined behavior – Drew McGowen Jul 30 '14 at 18:52
  • you are returning a pointer to a local variable (undefined behavior). – NetVipeC Jul 30 '14 at 18:52
  • It uses the operator function `operator+(std::string&, const char*)`. – David G Jul 30 '14 at 18:53
  • Why do you think `s += s2;` shouldn't work? What shouldn't work is `return s.c_str();` because it returns a pointer into an object that no longer exists when the caller gets it. – David Schwartz Jul 30 '14 at 19:03
  • @chris: This advice is debatable. I know of experienced C++ programmers who continue to use the old headers, whereas others argue for the new ones (just look at related past SO questions). – Christian Hackl Jul 30 '14 at 19:20
  • @ChristianHackl, They're officially deprecated per the standard. I prefer not to use deprecated things when there is no more functionality in them than in the newer ones. They buy you unoverloaded functions all in the global namespace. – chris Jul 30 '14 at 19:23
  • In general, adding pointers is not a good idea and usually doesn't make sense (Add your home address to your friends's address, as they behave like pointers). However, scalar quantities can be added to a pointer (My friend lives 3 houses south of my home). – Thomas Matthews Jul 30 '14 at 19:30
  • @chris: I know that they are officially deprecated. But that doesn't mean the decision was wise. Errare humanum est. I don't want to repeat all arguments in a short comment, but http://stackoverflow.com/questions/7596406/stdio-h-not-standard-in-c contains some good points. – Christian Hackl Jul 30 '14 at 19:33

3 Answers3

4

The variable s is local inside the append function. Once the append function returns that variable is destructed, leaving you with a pointer to a string that no longer exists. Using this pointer leads to undefined behavior.

My tip to you on how to solve this: Use std::string all the way!

Some programmer dude
  • 400,186
  • 35
  • 402
  • 621
0

you're adding const char* pointer to a std::string and that is possible (see this reference). it wouldn't be possible to make that operation on char* type (C style string).

however, you're returning a pointer to local variable, so once function append returns and gets popped of the stack, the string that your returned pointer is pointing to would not exist. this leads to an undefined behavior.

macfij
  • 3,093
  • 1
  • 19
  • 24
0

Class std::string has overloaded operator += for an operand of type const char *

basic_string& operator+=(const charT* s);

In fact it simply appends the string pointed to by this pointer to the contents of the object of type std::string allocating additionly memory if required. For example internally the overloaded operator could use standard C function strcat Conceptually it is similar to the following code snippet.

char s[12] = "Hello ";
const char *s2 = "World";

std::strcat( s, s2 );

Take into account that your program has undefined behaviour because total will be invalid after destroying local object s after exiting function append. So the next statemnent in main

printf("%s", total);

can result in undefined behaviour.

Vlad from Moscow
  • 301,070
  • 26
  • 186
  • 335