Reputation: 105
Reading data from the file is correct, owner, phone, tariff get values and output to the console, but when I pass them to the function, the owner pointer for some reason becomes empty and is not output when calling preOrder, although phone does not lose the pointer and is output to the console. What might be the problem?
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
typedef struct node{
char owner[10];
char phone[12];
int tariff;
struct node *left, *right;
} NODE, *pNODE;
pNODE addNode(char * owner, char * phone, int tariff, pNODE root);
void preOrder(pNODE root);
int main() {
srand(time(NULL));
pNODE root = NULL;
FILE* fp;
fp = fopen("./source/data.txt", "r");
char owner[10];
char phone[12];
int tariff;
while(!feof(fp)){
fscanf(fp, "%s", &owner);
printf("%s ", owner);
fscanf(fp, "%s", &phone);
printf("%s ", phone);
fscanf(fp, "%d", &tariff);
printf("%d\n", tariff);
root = addNode(owner, phone, tariff, root);
}
fclose(fp);
printf("%s\n", root->owner);
preOrder(root);
return 0;
}
pNODE addNode(char * owner, char * phone, int tariff, pNODE root){
if(!root){
root = malloc(sizeof(NODE));
if(root){
strcpy(root->owner, owner);
strcpy(root->phone, phone);
root->tariff = tariff;
root->left = NULL;
root->right = NULL;
}
}
else
if(tariff < root->tariff)
root->left = addNode(owner, phone, tariff, root->left);
else
root->right = addNode(owner, phone, tariff, root->right);
return root;
}
void preOrder(pNODE root){
if(root){
printf("%s %s %d", root->owner, root->phone, root->tariff);
preOrder(root->left);
preOrder(root->right);
}
}
Data in the file:
Ivan +79857465656 1
Mark +78345674534 2
Tom +78937478383 1
Petr +78293338475 3
Anna +79883743737 4
Upvotes: 0
Views: 29
Reputation: 781004
char phone[12]
is not big enough for your phone numbers. The phone numbers are 12 characters long, so the array needs at least 13 elements to allow for the trailing null byte.
Because of this you're writing outside the array bounds, causing undefined behavior.
You need to increase the size of both the local variable and the structure member.
Upvotes: 1