I used below codes to pass a value from vector to my cpp file. While i'm doing that, i got segmentation error in my main cpp? Is there anyway to pass the vector value to my main cpp? thx for the help

void Loadfile()
{
	//cout<<"this is used for loading file"<<endl;//check if the codes passing here
	string line;
    ifstream myfile;
    vector <string> myvector;
    
	myfile.open(DATAFILE);    // Open the datafile
	if (myfile.is_open())     //check If it worked
    {
			while (getline(myfile,line,'\n'))//get whole line from DATAFILE 
           {
											//cout<<i++<<endl;//to test if the codes work correctly
             myvector.push_back(line);		//store them in vector
            }

Dani AI

Generated

A few focused checks will usually find this kind of crash. is right to look at how the vector leaves Loadfile(); beyond that, look for three common causes that show up as a segfault in main: using a reference or pointer to data that no longer exists, indexing past the end of the container, or using pointers/iterators invalidated by container reallocation or modification.

Practical debugging steps that quickly locate the fault:

g++ -g -O0 -std=c++17 -fsanitize=address -o prog main.cpp
./prog                 # AddressSanitizer prints errors and backtraces
valgrind --leak-check=full ./prog
gdb --args ./prog      # run then use "bt" to get a stack trace

AddressSanitizer and Valgrind find invalid memory accesses; gdb gives a precise backtrace so you can see which line in main crashed.

Fix patterns to apply (do not re-use pointers into ephemeral memory):

  • Follow ’s suggestion or return a fresh container. Do not return a reference or pointer to a local object.
  • Never keep raw char*/const char* from string::c_str() or take addresses of elements if the vector will be modified later; reallocation invalidates those pointers (see cppreference on invalidation).
  • If external code must point into the vector, call reserve() first so pushes do not reallocate.
  • Replace unchecked operator[] uses with at() during debugging to catch out-of-range accesses.

Quick checklist: confirm the file actually opened, build with debug symbols and sanitizers, get a backtrace where the crash happens, and inspect any stored pointers/iterators that outlive the vector operations. If the crash persists, include a minimal reproducible example plus the sanitizer or gdb backtrace when asking for more help.

AddressSanitizer | Valgrind | cppreference: vector invalidation

Well, I can't say much just by looking at your (incomplete)code, but I wonder exactly how you are passing the vector to main() or any other function, as vector<string> myvector; remains a local variable, and looking at your definition of the function LoadFile() , it doesn't return anything.

To answer your second question, why not pass the vector to LoadFile() , so that it gets populated in that way, and remain usable after LoadFile() goes out of scope, like so:

void LoadFile(std::vector<std::string>& myvector)
{
     // Initialize variables
     // Open the file
     // Start reading
     while (getline(myfile,line,'\n'))
          myvector.push_back(line); // Note: you don't have to re-declare myvector
}

int main()
{
    // Some code
    
    std::vector<std::string> myvector;
    LoadFile(myvector);

    return 0;
}

You can also return the vector, instead of passing it by reference, but that's up to you.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.