sara
sara

Reputation: 3934

Qt - C++ string concatenation segmentation fault

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?

Upvotes: 0

Views: 1379

Answers (3)

ForEveR
ForEveR

Reputation: 55887

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.

Upvotes: 3

sara
sara

Reputation: 3934

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!

Upvotes: -1

Liron
Liron

Reputation: 2032

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?

Upvotes: -1

Related Questions