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?

Bruce
  • 7,094
  • 1
  • 25
  • 42
sara
  • 3,824
  • 9
  • 43
  • 71

3 Answers3

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.

ForEveR
  • 55,233
  • 2
  • 119
  • 133
  • 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. – sara Jul 23 '12 at 12:52
  • 1
    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. – Jens Jul 23 '12 at 13:11
-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?

Community
  • 1
  • 1
Liron
  • 2,012
  • 19
  • 39
  • Doh. Yeah, that would work too, so you have to make sure that all the strings above are QStrings. `QString("\Data\") + QString(someReference)` etc. – Liron Jul 23 '12 at 11:30
  • QString has + operator so it would work. Except that if you got a null pointer, it crashes... – Bruce Jul 23 '12 at 11:33
  • @LKM : not necessarily, look at the prototypes in his link. Moreover, pobjects can be constructed on the flight by compiler to fit. – Bruce Jul 23 '12 at 11:34
-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!

sara
  • 3,824
  • 9
  • 43
  • 71