Sign in to follow this  
ehmdjii

C++ extern char* does not change correctly

Recommended Posts

ehmdjii    238
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!

Share this post


Link to post
Share on other sites
OrangyTang    1298
"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).

Share this post


Link to post
Share on other sites
ehmdjii    238
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 ;-)

Share this post


Link to post
Share on other sites
Zahlman    1682
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?

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this