0

I'm new to c++, so I guess I fell into a newbyes C++ pitfall.

I tried to do the following:

QString  sdkInstallationDirectory=getenv("somEnv");

QString someSourceDir=sdkInstallationDirectory+"\\Data\\"+someReference+ "\\src";

and I get a segmentation fault.

I guess this is because of the concatenation of the const chars and insufficient memory allocated to the someSourceDir QString.

What exactly is my mistake? How can I do this concatenation?

3 Answers 3

3
char * getenv ( const char * name );

A null-terminated string with the value of the requested environment variable, or NULL if that environment variable does not exist.

Why you not check result?

EDIT.

So, check pointer is not necessary.

For historical reasons, QString distinguishes between a null string and an empty string. A null string is a string that is initialized using QString's default constructor or by passing (const char *)0 to the constructor.

Sign up to request clarification or add additional context in comments.

2 Comments

Well, the tool is installed by installer that creates the environment variable. No variable=no tool, I will check it as precaution of course, but it is not the cause. Anyway - great answer, and +1. I found the problem, and it was not related for the question, sorry.
QString can handle a Null-Pointer construction, the constructor QString(const char*) will create an empty QString with Unicode coding. The code provided by sara is perfectly fine and clear.
-1

You can't add strings together with a +. Try using a stringstream.

Something like:

stringstream ss;
ss << sdkInstallationDirectory << "\Data\" + someReference << "\src";
string str = ss.str();

Although, if you are using Qt, you shouldn't be joining paths as strings.

See How to build a full path string (safely) from separate strings?

3 Comments

Doh. Yeah, that would work too, so you have to make sure that all the strings above are QStrings. QString("\Data\") + QString(someReference) etc.
QString has + operator so it would work. Except that if you got a null pointer, it crashes...
@LKM : not necessarily, look at the prototypes in his link. Moreover, pobjects can be constructed on the flight by compiler to fit.
-1

Thank you all for your answers.

It appears that I was wrong, and the segmentation fault was caused a line before, where I created the reference I mentioned in the question.

I discovered it with further debugging.

Sorry for the confusion, and thank you again!

Comments

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.