• Welcome to Overclockers Forums! Join us to reply in threads, receive reduced ads, and to customize your site experience!

Need C++ help

Overclockers is supported by our readers. When you click a link to make a purchase, we may earn a commission. Learn More.

Zerix01

Member
Joined
Mar 12, 2007
I'm having some problems with passing a string to a class and dynamicly creating more of the class type. Since I'm still learning I created a new program that only does this one thing so I can test it out and see what works and what doesn't. I keep getting segment faults when I try to allocate new memory.

Code:
#include <iostream>
#include <string>
#include "stringh.h"

using namespace std;

int main()
{

int i = 0, a = 1;
string word;

St *str;
str = new St[a];

word = "Word";

for(i = 0; i != 3; i++){
a++;
cout << a <<endl; 
str[i].setVar(word);

cout << str[i].getVar();
cout << endl;
}

return 0;
}

And here is the header

Code:
class St
{
std::string w;

public:
	void setVar( std::string a)
	{
		w = a;
	}
	
	std::string getVar()
	{
		return w;
	}
};

The output looks like this

Code:
2
Word
3
Segmentation fault

2 <- so it increments without a problem
Word <- and the string was set into my class correctly
3 <- increments again
Segmentation fault <- I assume this means that although "a" was incremented to 2 and 3 it never dynamicly allocated the new memory and when I try to store my string in the new space it seg faults. What am I doing wrong?
 

Trombe

Member
Joined
Mar 13, 2005
Location
Austin, Texas
str[3] is beyond the bounds of str, as it was initialized with str = new St[a]; when a = 1.

you are getting confused with your i and a variables
 
OP
Zerix01

Zerix01

Member
Joined
Mar 12, 2007
Ah crap, I see what is going on. So I need to determine what 'a' should be before initializing str. I had thought I was able to do this before just only when using numbers instead of strings, so I thought it was a string issue.

Thanks.
 

FireMogle

Member
Joined
Apr 24, 2001
Location
Lawrence, KS
Code:
int main()
{

int i = 0, a = 1;
int b = a;
string word;

St *str;
str = new St[a];

word = "Word";

for(i = 0; i < a; i++){
b++;
cout << b << endl; 
str[i].setVar(word);

cout << str[i].getVar();
cout << endl;
}

return 0;
}

This should make it so that no matter the value of a you initialize the size of your array to be, your loop will always be valid.