首页 > 解决方案 > Segmentation fault (core dumped) while attempting to run a sorting algorithm for pointers

问题描述

I am attempting to create a sorting algorithm for three pointer variables based on the strings that are associated with them. However, every time I attempt to run the program, after I get past the first user data entry point, the Segmentation fault (core dump) error is thrown. I have looked on many sites to research this and have not been able to find an answer that works. I believe it is an error with the memory allocation of my pointer variables, but I have no idea how to fix it or where it is. What should I do to alleviate this? Here is some sample code:

//new data type
struct Balloon{
string message=""; //give the balloon object a message and a color
string color="";
};

/// main program
int main (void) {

//Instantiate three Balloon objects.
Balloon *front, *middle, *end, *spare;
front, middle, end, spare = new Balloon; //allocate storage for these variables.

//Ask the user what the messages and colors of the balloons are, and set those values to the pointer variables.

//first balloon
cout << "First balloon text: ";
cin >> front->message; //here is when the error is thrown
cout << "Color: ";
cin >> front->color;

I am new to Ubuntu and C++, and have only used Java before, so I apologize for any atrocious errors I may have unwittingly made. Thank you in advance for your help!

标签: c++sortingubuntusegmentation-faultg++

解决方案


front, middle, end, spare = new Balloon; //allocate storage for these variables.

这仅分配一个Balloon结构并分配spare为指向它的指针。没有分配其他指针。要分配所有气球,您需要单独执行每个气球:

front = new Balloon();
middle = new Balloon();
// etc.

如果您打开所有编译器警告,您将收到有关此错误的消息。例如,使用g++,您可以执行

g++ -Wall <filename>

推荐阅读