So, I am new to C++. I've researched Segmentation Fault (core dumped), memory allocation, and new/delete although I am having trouble understanding the concepts. I do believe my problem lies with memory allocation though and that's why I thought "delete" would have solved my problem. May someone please push me in the right direction?
Input
#include <iostream>
#include <string>
using namespace std;
struct CandyBar
{
string name;
double weight;
int calories;
} ;
int main()
{
CandyBar* backpack = new CandyBar[3];
backpack[0] = {"Choco Chalk", 5.1, 725};
backpack[1] = {"Twisty String", 1.8, 300};
backpack[2] = {"Gummy Nums", 4.4, 475};
cout << "Name\t\tWeight\tCalories" << endl << endl;
for (int x = 0; x < 4; x++)
{
cout << backpack[x].name << "\t" << backpack[x].weight << "\t" << backpack[x].calories << endl;
}
delete backpack;
return 0;
}
Output
Name Weight Calories
Choco Chalk 5.1 725
Twisty String 1.8 300
Gummy Nums 4.4 475
(Segmentation fault) core dumped
I see two bugs:
Your loop for (x = 0; x < 4; x++)
will iterate through x values 0, 1, 2, 3. However, since you allocated backpack
with new Candybar[3]
, backpack
points to only enough memory to hold 3 CandyBar
s, namely backpack[0], backpack[1], backpack[2]
. As it stands, on its fourth time through, your loop will attempt to access backpack[3]
, which is off the end of the array.
When you allocate memory with new[]
(as you did since you allocated an array of CandyBar
), you have to deallocate it with delete[]
, not just plain delete
. See delete vs delete[] operators in C++ .
When I changed your loop exit condition to x < 3
and your deallocation to delete[] backpack;
, the program worked for me.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.