Inside the array sometimes got weird symbol inside

Garbage in char pointer array

Posted 30 January 2010 - 11:00 AM

Hi,
This assignment suppose to create a set with random character inside it and do some arithmetic function for example Union,Subset,Intersection ..
The character inside the array can't be duplicate.
We suppose to explore pointer and only see the movement pointer in this assignment.

So here is my problem , sometimes i got some weird symbol when i generate the set.
It often appear at the back of the set or when the set is empty set
Could someone please let me know how to terminate char pointer array properly ?
The menu 0 can successfully generate a set with no garbage value
But other function ex : Union,equality ,etc
Sometimes got weird characters inside
(Will only find it if we generate it few times)
But im really curious is there anyway to get rid of this?

Re: Garbage in char pointer array

Posted 31 January 2010 - 02:35 PM

I didn't check your entire code but the problem that you noticed is occurring in constructSet(). See comments in corrected code:

void constructSet (ptr s,int size)
{
// You must initialize the array before using it. Otherwise checkSet() is
// checking against undefined garbage.
for( int j = 0; j < size; ++j ) {
*(s + j) = -1;
}
// ptr ch; // see comment below
char ch;
ptr first = s;
int i=0;
while (i<size) // not i <= size; when i==size you are beyond the end of the array
{
// Why are you creating a local array when you only need one char? (Notice that you have
// been using only the first element of this array.)
// ch = new char[size];
// *ch =static_cast <char> ((rand()%26) + 65); // *ch is FIRST element in local array
// In the following, ch is a char:
ch = static_cast <char> ((rand()%26) + 65);
if (checkSet (ch , first , s)== false)
{
*s = ch;
++s;
++i; // moved here instead
}
// i++; // Not here; this moves on to the next element even when
// the if condition fails, leaving an element undefined.
}
}

You have another serious error in Union(). Although you may not have encountered it yet, it can cause corrupted data or a segmentation fault. In that function, you allocate memory for two arrays of size MAX. You then add elements from the first array to the end of the second array. But the set union could be as big as 2*MAX so it is very likely that you will at times write beyond the bounds of that array. Therefore, you should make the receiving (second) array twice as big.

By the way, since you are (correctly) handling these arrays as ordinary arrays, not strings, the string termination character '\0' is irrelevant here. But YOU have to make sure that your code keeps track of the array bounds. The compiler won't do it for you.