View Full Version : c++ help

Jul 12, 2007, 03:54 PM
the following program compiles fine, but after entering an item's name after selecting 'e' causes gdb to run, and in terminal it says segmentation fault which means im trying to enter something that doesnt exist but why?

by the way the program enters items input by the user into a structure. input() and enter() are the two functions that are causing me trouble, im not sure why.


#include <iostream>
#include <cctype>
#include <cstring>
#include <cstdlib>
using namespace std;

const int SIZE = 10;

struct inventory{
char item[40];
double cost;
int retail;
int on_hand;
int lead_time;

void init_list(), enter(), display();
void update(), input(int i);
int menu();

int main () {
char choice;

choice = menu();
case 'e': enter();
case 'd': display();
case 'u': update();
case 'q': return 0;
return 0;

// initialize a list
void init_list(){
int t;

// makes that element empty.
for(t=0; t < SIZE;t++)
*invntry[t].item = '\0';
// get a menu selection
int menu(){
char ch;

cout << '\n';

cout << "(E)nter\n(D)isplay\n(U)pdate\n(Q)uit\n\n";
cout << "Choose one: ";
cin >> ch;
}while(!strchr("eduq", tolower(ch)));
return tolower(ch);
//input the information
void input(int i){
//enter the information
cout << "Item: ";
cin >> invntry[i].item;

cout << "Cost: ";
cin >> invntry[i].cost;

cout << "Retail: ";
cin >> invntry[i].retail;

cout << "On hand: ";
cin >> invntry[i].on_hand;

cout << "Lead time to resupply(in days): ";
cin >> invntry[i].lead_time;
// enters items into the list
void enter(){
int i;

// finds a free structure
for(int i = 0; i < SIZE; i++)

if(i == SIZE){
cout << "List Full\n";

// modify an existing item
void update(){
int i;
char name[80];

cout << "Enter item: ";
cin >> name;

for(i = 0; i < SIZE; i++)
if(!strcmp(name, invntry[i].item))break;

if(i == SIZE){
cout << "Item not found";
void display(){
int t;
for(t = 0; t < SIZE; t++){
cout << invntry[t].item << '\n';
cout << "Cost $" << invntry[t].cost << '\n';
cout << "Retail Price $" << invntry[t].retail;
cout << "on hand: " << invntry[t].on_hand;
cout << "\nResupply time: ";
cout << invntry[t].lead_time << " days\n\n";


Jul 12, 2007, 04:51 PM
enter() is passing an uninitialized variable i to input. Since i has a random value, when you start writing to invntry[i], the program bombs.

You just want to remove the "int" from your for loop in enter().

That is causing a new variable called i to be used inside the loop. When the loop terminates that i goes away and you are left with the uninitialized i which you pass to enter...

See what I mean?

Jul 12, 2007, 04:56 PM
Also, you can use cin.width(40); before the call to cin >> invntry[i].item. This will prevent the buffer overflow on item if the user enters a name that is too long (the input is just truncated to the first 39 chars + 1 for the null terminator).

Jul 12, 2007, 05:00 PM
thanks for the help.