Reputation: 87
I have built a BST that holds album names and years and It constructed according to years.But I want to enter album names and it should give a year. So I built this code part :
int FindString(treeAlbum *node,char albumTitle[])
{
FindString(node->Left,albumTitle);
FindString(node->Right,albumTitle);
if(!strcpy( node->albumTitle, albumTitle))
{
return node->year;
}
}
And treeAlbum struct
struct treeAlbum{
char albumTitle[100];
int year;
struct treeAlbum *Left;
struct treeAlbum *Right;
}
Finally, This code give an error ( Segmentation Fault). How can I fix this ? Thank You.
Upvotes: 0
Views: 337
Reputation: 6984
You want to use strcmp
, not strcpy
. You should evaluate the result of two FindString()
calls and continue only, when they failed.
Upvotes: 0
Reputation: 3302
The first thing you do in FindString
is call FindString
again with node->Left
. Either node->Left
eventually is null
(if your tree is correctly constructed) which will cause a segfault or it is an earlier node in the tree (in which case your recursion will cause the stack to fill up). Checking for the null case is certainly required!
Upvotes: 0
Reputation: 2261
My best guess for the segmentation fault is that you aren't checking for your base case.
int FindString(treeAlbum *node,char albumTitle[])
{
if (!node)
{
// Return something sane here
return ERROR_NOT_FOUND;
}
FindString(node->Left,albumTitle);
FindString(node->Right,albumTitle);
if(!strcpy( node->albumTitle, albumTitle))
{
return node->year;
}
}
However, your code has some other issues:
FindString
. Right now you're not doing anything.strcpy
, but you probably mean strcmp
.Upvotes: 1