warning: adress of local variable '<variable>' returned

I am trying to pull from my .bashrc an environment variable CUSTPATH. I want to store the various directories in this variable in a vector and then return a pointer to said vector. Here is my code.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
#include<iostream>
#include<vector>
#include<string>

using namespace std;

std::vector<std::string>* getCustPath(){
	std::string const key = "CUSTPATH";
	char * val;
	val = getenv(key.c_str());
	std::vector<std::string> locations;
	if (val == NULL) {
		cout << "CUSTPATH not set. Please set CUSTPATH environment variable" << endl;
		exit(0);
	}
	else {
		std::string buf = val;
		while (!buf.empty()){
			int pos = buf.find(':');
			if (pos!=string::npos){
				locations.push_back(buf.substr(0,pos));
				buf.erase(0,pos+1);
			}
			else {
				locations.push_back(buf);
				buf.erase(0,buf.size());
			}//else
		}//while
		for (int i=0; i<locations.size(); i++) cout << locations[i] << endl;
		return &locations;
	}//else
}

int main (){
	std::vector<std::string>* custPaths;
	pdbPaths=getCustPath();
	cout << (*custPaths)[0] << endl;
}


I get the following error when trying to compile.

 
getCustVar.cpp:11 warning: address of local variable 'locations' returned


Running the code gives the proper output for the for loop in the getCustPath function. However, the output for the final cout in main is incorrect.

1
2
3
4
5
6
>./getCustVar.out
/path1
/path2
/path3

>
The error is just what the warning says. You're returning a pointer to a local vector, which is destroyed when the function exits. Return by value instead.
Last edited on
Topic archived. No new replies allowed.