Reputation: 791
readFruit.name
is initialized to NULL
before I try to initialize it as a char array. I included size
to see if that was the culprit but it is exactly what it should be depending on my input. No matter what length tempString
is, readFruit.name
is allocated around 25 "characters" in memory and they're all garbage. Why isn't it being allocated a space the size of tempString.length()
and how can I fix it?
relevant CPP
std::istream & operator>>(std::istream &is, Fruit &readFruit)
{
string tempString;
is >> tempString;
int size = tempString.length();
readFruit.name = new char[tempString.length()];
for(int i = 0; i < (int)tempString.length(); i++)
{
readFruit.name[i] = tempString[i];
}
for(int i =0; i < CODE_LEN; i++)
{
is >> readFruit.code[i];
}
return is;
}
Relevant H file (constructor)
#ifndef _FRUIT_H
#define _FRUIT_H
#include <cstring>
#include <sstream>
#include <iomanip>
#include <iostream>
enum { CODE_LEN = 4 };
enum { MAX_NAME_LEN = 30 };
class Fruit
{
private:
char *name;
char code[CODE_LEN];
public:
Fruit(const Fruit &temp);
Fruit(){name = NULL;};
bool operator<(const Fruit& tempFruit);
friend std::ostream & operator<<(std::ostream &os, const Fruit& printFruit);
bool operator==(const Fruit& other){return *name == *other.name;};
bool operator!=(const Fruit& other){return *name != *other.name;};
friend std::istream & operator>>(std::istream& is, Fruit& readFruit);
};
#endif
Upvotes: 0
Views: 188
Reputation: 47824
If you're trying to print readFruit.name
, it will display garbage value until it finds a null termination, that's what I assume you saying 25 characters "all garbage"
Allocated memory like this :
readFruit.name = new char[tempString.length()+1];
And after for
loop do:
readFruit.name[i] ='\0'; // C strings are null terminated
Upvotes: 4
Reputation: 77334
To solve your problem, you need to null-terminate your name
character array. Right now you copied all characters, but you need to have a binary zero character at the end for all string functions to work. So you need to allocate one char more and write a '\0'
to it.
That said: use std::string
for your fruit's name. There is no reason to help yourself to a ton of self-made bugs by staying with a character array.
Upvotes: 3