I am implementing a knowledge tree in c that can read from a file. I am getting a seg fault in my newStr function. I\'m not able to test the rest of my code with this problem. I
There might be several more, but here's some points on what's wrong:
Your newStr function is just very, very wrong. At a guess you'd want something like:
char * newStr (char * charBuffer)
{
char *newStr;
if(charBuffer[0] == 'A' || charBuffer[0] == 'Q') {
newStr = strdup(&charBuffer[1]);
} else {
newStr = strdup("");
}
if(newStr == NULL) {
//handle error
}
return newStr;
}
You can't cast a string to a char like you do here:
if(ans[0] == (char)"Y" || ans[0] == (char)"y")
Do instead(same for similar code elsewhere too)
if(ans[0] =='Y' || ans[0] == 'y')
Same as above when you call putc, don't do
fputc((char)"A", f);
Do
fputc('A', f);
scanf needs a format string, don't do:
scanf(ans);
Do e.g. (or just use fgets again)
if(scanf("%99s",ans) != 1) {
//handle error
}
"+" operator as string concatenation does not work in c.
If you actually want to copy the a string use strdup()
. This function allocates memory and copies the string into it.
Don't forget to free the allocated memory when done using it.
char * newStr (char * charBuffer)
{
int i;
int length = strlen(charBuffer);
char newStr;
if(charBuffer[0] == 'A' || charBuffer[0] == 'Q'){
for(i=1; i<length; i++)
newStr += charBuffer[i];
}
return (newStr + "\0");
}
Well, there's a few interesting things here... To get down to brass tacks, you're trying to copy the contents of a character pointer into another and this function isn't going to do that. All you're really doing is summing the value of each char in charBuffer into newStr because a char is really just an 8-bit integer and then you return that integer as a pointer through an implicit cast so it is now being treated as a memory address.
You should look to use strdup(), as has been noted, since this is exactly what the function is supposed to do. No need to reinvent the wheel. :)