C++ extern char* does not change correctly

Started by
2 comments, last by Zahlman 15 years, 12 months ago
hello, i have this small little program where i would like to change the contents of a char* variable in another file.

#include <windows.h>
#include "somefile.h"

char* sometext = "hello world";

int APIENTRY WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR lpCmdLine, int nCmdShow) {

//before this line sometext contains hello world
	changetext();
//after this line sometext contains gibberish

	return 0;
}

the somefile.h looks like this

#pragma once

#include <windows.h>
#include <string>

using namespace std;

extern char* sometext;

void changetext() {

	string s = "a new text";

//before this line sometext contains hello world
	sometext = (char*) s.c_str();
//after this line sometext contains a new text

}

why is the "a new text" string not correctly given back to the main function? thanks!
Advertisement
"string s" creates a std::string on the stack, and .c_str() only gets a pointer to the internal memory of the std::string. So when "s" goes out of scope at the end of changetext(), "s" is destroyed and it deletes all memory it allocated, meaning that the memory pointed to by "sometext" is now invalid.

Without knowing what you're aiming on doing I don't know what to suggest to fix it though. Why not just have changetext() return a std::string (and possibly accept one as a parameter if it needs to change the original).
thanks! that makes sense now!

this code is just an example, in the real situation the changetext function overrides another one so unfortunately i cant have it return a string or provide an additional parameter, so i used extern. (i know it's evil ;-)
Quote:Original post by ehmdjii
thanks! that makes sense now!

this code is just an example, in the real situation the changetext function overrides another one so unfortunately i cant have it return a string or provide an additional parameter, so i used extern. (i know it's evil ;-)


Why do you need to override the function to do something different from the "default" version? What's the string for, anyway? What is the function nominally supposed to do?

This topic is closed to new replies.

Advertisement