program crashes

Hello guys, I was trying to create a program that reads data from a txt file and store that data to an array. but unfortunately, my program started tp crash after i made a char function that gets the values of the different variables, let's not talk too much, here is my code, i hope we will find the error.

#include <stdio.h>
#include <iostream>
#include <string.h>

char GetData(char buffer[]);

enum uInfo
{
uName,
uGender,
uAge,
uCash
};

uInfo UserInfo[4];

int main()
{
FILE * pFile;
char buffer [100];

pFile = fopen ("myfile.txt" , "r");
if (pFile == NULL) perror ("Error opening file");
else
{
while ( ! feof (pFile) )
{
if ( fgets (buffer , 100 , pFile) == NULL ) break;
fputs (buffer , stdout);
printf("/ %s", GetData(buffer));
}
fclose (pFile);
}
return 0;
}

char GetData(char buffer[])
{
char *p;
//p = strtok(buffer, ":");
p = strtok(NULL, ":");
return *p;
}
You've used strtok() incorrectly.

Well, there's quite a bit that's not right, biut that's the cause of the crash.
Last edited on
when i add printf("%d", p); to the end of the GetData(char) function, it works perfectly. I think that the error is return *p;
You have two problems:

printf("/ %s", GetData(buffer)); // printf expects a 0 terminated string but gets a char

return *p; // This causes undefined behavior if p is a nullptr
I think that doing so increase the amount of complexity within the code and unless you use programs as checkmarx as help it is going to be a hard job detecting all the errors among the code.
Good luck.
Registered users can post here. Sign in or register to post.