This question already has answers here:
Closed 12 years ago.
Possible Duplicate:
Seg Fault in Knowledge Tree
I can't pinpoint my seg fault in my information tree. It is supposed to read from file or get user input if the file does not exist. It's supposed to guess the animal based on yes or no questions. I have limited experience with c so any help would be greatly appreciated.
.c file
#include<stdio.h>
#include<stdlib.h>
#include"animal.h"
#include<string.h>
#include<assert.h>
/*returns a new node for the given value*/
struct Node * newNode (char *newValue)
{
printf("Node test");
struct Node * tree;
tree = (struct Node*)malloc(sizeof(struct Node));
tree -> value = newStr(newValue);
printf("Node test");
return tree;
}
/* returns a new string with value passed as an argument*/
char * newStr (char * charBuffer)
{
printf("Str test");
char *newstr;
if(charBuffer[0] == 'A' || charBuffer[0] == 'Q'){
newstr = strdup(&charBuffer[1]);
}else{
newstr = strdup("");
}
return newstr;
}
/*Read from a File and create a tree*/
struct Node * readATree(FILE * f)
{
printf("ReadATree test");
char c;
char buffer[100];
struct Node * newTree;
c = fgetc(f);
if (c == 'A'){
fgets(buffer, 100, f);
newTree = newNode(newStr(buffer));
newTree -> left = NULL;
newTree -> right = NULL;
}
else{
fgets(buffer, 100, f);
newTree = newNode(newStr(buffer));
newTree->left = readATree(f);
newTree->right = (struct Node *) readATree(f);
}
return newTree;
}
/*Write Tree to a File*/
void writeAFile(struct Node* tree, FILE * f)
{
printf("WriteFile test");
char buffer[100];
strcpy(buffer, tree->value);
if(tree != 0){
if(tree->left == NULL && tree->right == NULL){
fputc('A', f);
fputs(buffer,f);
} else{
fputc('Q',f);
fputs(buffer,f);
writeAFile(tree->left, f);
writeAFile(tree->right,f);
}
}
}
/*The play should start from here*/
int main (){
printf("main test");
struct Node* node;
struct Node* root;
char ans[100];
char q[100];
FILE * f;
f = fopen("animal.txt", "r+");
if(f != NULL)
readATree(f);
else{
node = newNode("Does it meow?");
node->right = NULL;
node->right->right=NULL;
node->left->left=NULL;
node->left=newNode("Cat");
root = node;
}
while(node->left != NULL && node->right != NULL){
printf(node->value);
scanf(ans);
if(ans[0] == 'Y' || ans[0] == 'y')
node = node->left;
else if(ans[0] == 'N' || ans[0] == 'n')
node = node->right;
else
printf("That is not a valid input.\n");
}
if(ans[0] == 'Y' || ans[0] == 'y')
printf("I win!");
else if(ans[0] == 'N' || ans[0] == 'n'){
printf("What is your animal?\n");
scanf("%s",ans);
printf("Please enter a yes or no question that is true about %s?\n", ans);
scanf("%s",q);
node->right = newNode(q);
node->right->left = newNode(ans);
node->right->right = NULL;
}
writeAFile(root,f);
fclose(f);
return 0;
}
.h
#include<stdio.h>
struct Node {
char *value;
struct Node * left;
struct Node * right;
};
struct Node * newNode (char *newValue) ;
char * newStr (char * charBuffer);
struct Node * readATree(FILE * f);
void writeAFile(struct Node* tree, FILE * f);
Don't force the good people of SO to wade through and debug your code! Also, don't keep repeating your question. The reason it wasn't answered to your satisfaction earlier is that people were unwilling to compensate for your laziness.
That's what debuggers are for. Run your code in a debugger, and it will tell you when you're accessing a null pointer.
If you don't have a debugger, throw a bunch of print statements into your program. If you run your program, the last printout before the crash will be just above the place where your segmentation fault occurred. You may want to add even more print statements near that point, perhaps dumping out some pointer values.
From a cursory glance at the code:
node->right = NULL;
node->right->right=NULL;
The second line here will access a NULL pointer, which will cause a segfault.
In general, running the code in a debugger will let you see which line caused the error.
I'm guessing that these warnings are a clue:
animal.c: In function ‘main’:
animal.c:95: warning: format not a string literal and no format arguments
animal.c:96: warning: format not a string literal and no format arguments
Related
I'm making a phonebook program with a binary search tree. Whenever I try to input a new data, the segmentation fault occurs. First, I have type definition structure which name is phoneData.
typedef struct phoneData {
char name[NAME_LEN];
char phoneNum[PHONE_LEN];
struct phoneData *right, *left;
} phoneData;
void InputPhoneData()
{ //phoneData *pData;
char name[NAME_LEN];
char phoneNum[PHONE_LEN];
/*if ((pData = (phoneData*)malloc(sizeof(phoneData))) == NULL) {
fprintf(stderr, "Memory Allocation failed\n");
return;
}*/
fputs("이름 입력: ", stdout);
if (fgetString(name, NAME_LEN, stdin) == 1) {
getchar();
return;
}
fputs("전화번호 입력: ", stdout);
if (fgetString(phoneNum, PHONE_LEN, stdin) == 1) {
getchar();
return;
}
insert_node(name, phoneNum);
numOfData++;
fputs("입력이 완료되었습니다.", stdout);
getchar();
}
And this is the function which I call to input a data. Please don't mind the Korean sentences. In the function, I call another function insert_node. This is the function which inserts the binary search tree node.
void insert_node(char name[], char phoneNum[])
{
phoneData *p, *t;
phoneData *n;
t = *root;
p = NULL;
while (t != NULL) {
if (strcmp(name, t->name) == 0)
return;
p = t;
if (strcmp(name, p->name) < 0)
t = p->left;
else
t = p->right;
}
n = (phoneData*)malloc(sizeof(phoneData));
if (n == NULL)
return;
strcpy(n->name, name);
strcpy(n->phoneNum, phoneNum);
n->left = n->right = NULL;
if (p != NULL) {
if (strcmp(p->name, name) < 0)
p->left = n;
else
p->right = n;
}
else
*root = n;
}
I'm still wondering which is the part that I'm getting a segmentation fault. I already checked the fgetString function, and it seems to be okay. Did I make any mistakes on InputPhoneData function or insert_node function?
And by the way, the variable 'root' is a global variable which is a double pointer initialized as NULL. (phoneData **root = NULL;)
That's your problem right there. *root will dereference a NULL pointer.
Change the declaration to:
phoneData *root = NULL;
and replace *root with root and root with &root in the rest of your code.
It will be easy, fun and interesting to debug such kind of issues.
Try to debug using gdb :)
You can check following link,
http://www.thegeekstuff.com/2010/03/debug-c-program-using-gdb
Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 8 years ago.
Improve this question
I decided that I wanted to make a program in C that would take a user input and do things with a hash table... When I go to put in something it gets a segmentation fault at line 32. This being the following:
if (!hashTable[hashIndex].head) {
Rest of code:
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
struct hash *hashTable = NULL;
int eleCount = 0;
struct node {
int key;
char name[1024];
struct node *next;
};
struct hash {
struct node *head;
int count;
};
struct node * createNode(int key, char *name) {
struct node *newnode;
newnode = (struct node *)malloc(sizeof(struct node));
newnode->key = key;
strcpy(newnode->name, name);
newnode->next = NULL;
return newnode;
}
void insertToHash(int key, char *name) {
int hashIndex = key % eleCount;
struct node *newnode = createNode(key, name);
if (!hashTable[hashIndex].head) {
hashTable[hashIndex].head = newnode;
hashTable[hashIndex].count = 1;
return;
}
newnode->next = (hashTable[hashIndex].head);
hashTable[hashIndex].head = newnode;
hashTable[hashIndex].count++;
return;
}
void deleteFromHash(int key) {
int hashIndex = key % eleCount, flag = 0;
struct node *temp, *myNode;
myNode = hashTable[hashIndex].head;
if (!myNode) {
printf("Word not in hash Table!!\n");
return;
}
temp = myNode;
while (myNode != NULL) {
if (myNode->key == key) {
flag = 1;
if (myNode == hashTable[hashIndex].head)
hashTable[hashIndex].head = myNode->next;
else
temp->next = myNode->next;
hashTable[hashIndex].count--;
free(myNode);
break;
}
temp = myNode;
myNode = myNode->next;
}
if (flag)
printf("Word deleted from Hash Table by the power of Grey Skull\n");
else
printf("Word is not present in hash Table!\n");
return;
}
void searchInHash(int key) {
int hashIndex = key % eleCount, flag = 0;
struct node *myNode;
myNode = hashTable[hashIndex].head;
if (!myNode) {
printf("Searched word not in hash table\n");
return;
}
while (myNode != NULL) {
if (myNode->key == key) {
printf("Key : %d\n", myNode->key);
printf("Name : %s\n", myNode->name);
flag = 1;
break;
}
myNode = myNode->next;
}
if (!flag)
printf("Searched word not in hash table\n");
return;
}
void display() {
struct node *myNode;
int i;
for (i = 0; i < eleCount; i++) {
if (hashTable[i].count == 0)
continue;
myNode = hashTable[i].head;
if (!myNode)
continue;
printf("Key Word\n");
printf("----------------\n");
while (myNode != NULL) {
printf("%-12d", myNode->key);
printf("%-15s", myNode->name);
myNode = myNode->next;
}
}
return;
}
int main() {
int elecount, ch, key, i;
char name[1024],cas[5];
eleCount = 23;
hashTable = (struct hash *)calloc(elecount, sizeof (struct hash));
while (1) {
printf("\nword: Insert word\n#d: word Delete word\n");
printf("#s word: Search for word\n#p: Display hash table\n#Q: Exit\n");
printf("Enter your choice:");
fgets(name, 1023, stdin);
if(sscanf(name,"#d",&cas)==1)
{//delete
i=2;
while("name[i]"!="\n")
{key=key+i;
i++;}
deleteFromHash(key);
}
else if(sscanf(name,"#s",&cas)==1)
{//search
i=2;
while("name[i]"!="\n")
{key=key+i;
i++;}
searchInHash(key);
}
else if(sscanf(name,"#p",&cas)==1)
{//print
display();
}
else if(sscanf(name,"#Q",&cas)==1)
{//Quit
exit(0);
}
else
{//insert
while("name[i]"!="\n")
{key=key+i;
i++;}
name[strlen(name) - 1] = '\0';
insertToHash(key, name);
}
}
return 0;
}
Here is what I see as problems with the posted code:
1) the first parameter to calloc() is not initialized
2) the returned value from calloc is not checked to assure operation was successful
3) the returned value from calloc was cast and it should not be
4) the 'ch' variable is unused
5) this line: while("name[i]"!="\n") should be: while( name[i] != '\n')
6) the returned value form fgets() is not checked to assure successful operation
7) the format strings for the sscanf() statements are using '#' when they should be using '%'
8) variable eleCount not used
9) the struct definitions 'node' and 'hash' need to be before any usage of those definitions
10) the returned value from malloc should not be cast
11) the returned value from malloc is not checked to assure successful operation
12) the lines like this: 'else if(sscanf(name,"#Q",&cas)==1)' are not correct. they should be similar to:
else if(sscanf(name,"#Q",&cas)!=1)
{ // then sscanf failed
perror( "sscanf failed" );
exit( EXIT_FAILURE );
}
// implied else, sscanf successful
....
13) given the input description and the code following the calls to sscanf(), the sscan only needs to be called for a char input '%c'
then a switch statement on that char.
the cases of the switch statement would be the checks for the various commands
for those commands that need a 'name' to operate with, then there needs to be a if( 1 != sscanf( name, " %s", &cas ) )
// handle error
// implied else
// apply command to the input name
14) the array 'cas[]' only has 5 char elements
so if a parameter is greater than 4 characters then there will ve a buffer overrun, resulting in undefined behaviour and can/will lead to a seg fault event.
15) I think this line: 'key=key+i;' is not doing what the OP expects.
16) i think this line: 'insertToHash(key, name);' is not doing what the OP expects
I think I understand what the OP was trying to accomplish, but the posted code is not even close and does not even come close to compiling.
Suggest OP enable all warnings in their compiler, fix the warnings and errors,then do some reasonable debug activity, then if they still are having problems, then repost the question.
As others already said, your calloc in the main function uses the uninitialized variable elecount instead of eleCount. I recommend not using the same name for global and local variables with the only difference being the capitalization. You see why.
Also before you check the .head component you should check the variable itself.
So first check for hashTable, then you do the other check.
Otherwise you might check a components existence at NULL.
i am trying to write a program that will do the following
-read a file from std in
-read each line, and add each line to a binary tree
*if name is already in binary tree,dont add the name to the tree again but update its count of repititions
-print out the binary tree
the file being read in looks something like
dylan
bob
dylan
randall
randall
so when i print out the binary tree i would like it to print out
bob 1
dylan 2
randall 2
i was able to successfully print out the names without worrying about repetitions. I have commented out the blocks of code that mess my program up which is anything interacting with my search function that i added after the fact to take care of repetitions. The code builds a binary tree with each "leave" being a structure of 4 parts,the name,thecount,and the pointers to left and right childs.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
struct node {
char* name;
int count;
struct node* left;
struct node* right;
};
struct node* addNode(char* string);
void insert(struct node *root, char* stringgg);
void preorder(struct node *root);
int search(struct node* leaf,char* string2find);
int main()
{
char buffer[20];
struct node *root = NULL;
while( fgets(buffer, sizeof(buffer), stdin) != NULL )
{
if(root == NULL)
root = addNode(buffer);
else
insert(root,buffer);
}
preorder(root);
}
struct node* addNode(char* string)
{
struct node *temp = malloc(sizeof(struct node));
temp->name = malloc(strlen(string) + 1);
strcpy(temp->name,string);
temp->left = NULL;
temp->right = NULL;
return temp;
}
void insert(struct node *root, char* stringgg)
{
/* int flag = 5;
flag = search(root,stringgg);
if(flag == 1)
return; */
if(strcmp(stringgg,root->name) < 0)
{
if(root->left == NULL)
root->left = addNode(stringgg);
else
insert(root->left, stringgg);
}
else
{
if(root->right == NULL)
root->right = addNode(stringgg);
else
insert(root->right,stringgg);
}
}
/*int search(struct node* leaf,char* string2find)
{
if(strcmp(string2find,leaf->name) == 0)
{
leaf->count = leaf->count + 1;
return 1;
}
else if(strcmp(string2find,leaf->name) < 0)
{
return search(leaf->left,string2find);
}
else
{
return search(leaf->right,string2find);
}
return 0;
} */
void preorder(struct node *root)
{
if(root == NULL)
return;
printf("%s",root->name);
preorder(root->left);
preorder(root->right);
}
the above code prints out all the names even if there already in a tree. I was hoping that someone would be able to point out my search function errors so that it wont cause a segmentation fault when printing. Possible causes may be my inappropriate use of the return function in which i am trying to return to main if flag == 1 which means match was found so dont addnodes. but if flag does not equal 1 no match was found so go about adding nodes.
at main
while( fgets(buffer, sizeof(buffer), stdin) != NULL ){
char *p = strchr(buffer, '\n');
if(p) *p=0;//remove '\n'
at addNode
temp->count = 1;//initialize counter
return temp;
at insert
void insert(struct node *root, char* stringgg){
int cmp_stat = strcmp(stringgg,root->name);
if(cmp_stat == 0)
root->count++;
else if(cmp_stat < 0) {
if(root->left == NULL)
root->left = addNode(stringgg);
else
insert(root->left, stringgg);
} else {
if(root->right == NULL)
root->right = addNode(stringgg);
else
insert(root->right,stringgg);
}
}
at preorder
printf("%s %d\n",root->name, root->count);
The error is in searching for the very first item in the empty tree — you call
search(root, stringgg)
but root is NULL, so in search() you call
strcmp(string2find, leaf->name)
with leaf == NULL and the program crashes.
A cure: do not search BEFORE you update your tree, but rather search TO update it.
struct node* update(struct node* nd, const char* str)
{
int cmp;
// (sub)tree is empty? - create a new node with cnt==1
if(nd == NULL)
return CreateNode(str);
// test if the node found
cmp = strcmp(str, nd->name);
if(cmp == 0) // YES
nd->count ++; // update the counter
else if(cmp < 0) // NO - search in a subtree
nd->left = update(nd->left, str);
else
nd->right = update(nd->right, str);
return nd; // return the updated subtree
}
Then in main() you just update the tree and store it:
root = update(root, buffer);
Actually, the root value will change only once, on the first call, and all subsequent assignments will not change its value. However that makes the code much more readable.
The first time addToEnd() is called it works but the second time it crashes the program. I've been trying to debug it and found it happens when head->next happens. I'm a little confused because it's just being read, can that crash the program? If yes how can you possible itterate through the file?
It seems to work on certain values of entry but not others. If two entry's are the same and composed all of one letter it crashes. So if addToEnd(head, "aaaaaaaaa") is called then addToEnd(head, "aaaaaaaaa") is called the program crashes but if addToEnd(head, "aaaaaaaaa") then addToEnd(head, "aaaaaaaab") it is fine.
Here is 100% all of the code
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <stdbool.h>
typedef struct node
{
char entry[21];
struct node* next;
} node;
void readDic();
void reverStr(char *str);
bool isInDic(char *reversed);
void addToEnd(node* head, char entry[21]);
unsigned int searchAndDestroy(node **head, char *entry);
void printList(node* head);
int main()
{
printf("Hello\n");
readDic();
printf("Goodbye!");
return EXIT_SUCCESS;
}
void readDic()
{
FILE* words;
char singleLine[21];
words = fopen("words.txt", "r");
node* head = malloc(sizeof(node));
fscanf(words, "%20s", head->entry);//need to do this initially
head->next = NULL;
printf("here 0");
printf("here 0.1");
if(words == NULL)
exit(EXIT_FAILURE);
printf("here 0.5");
while(fscanf(words, "%20s", singleLine) == 1)assigned input terms
{
printf("\nhere 0.6\n|%s|", singleLine);
addToEnd(head, singleLine);//problem here
printf("here 0.7");
reverStr(singleLine);
printf("here 1");
if(isInDic(singleLine)){
printf("here 2");
searchAndDestroy(&head, singleLine);
printf("here 3");
}
}
printf("here 4");
fclose(words);
printList(head);
printf("here 5");
}
//http://stackoverflow.com/questions/198199/how-do-you-reverse-a-string-in-place-in-c-or-c
/* PRE: str must be either NULL or a pointer to a
* (possibly empty) null-terminated string. */
void reverStr(char *str)
{
char temp, *end_ptr;
/* If str is NULL or empty, do nothing */
if(str == NULL || !(*str))
return;
end_ptr = str + strlen(str) - 1;
/* Swap the chars */
while( end_ptr > str )
{
temp = *str;
*str = *end_ptr;
*end_ptr = temp;
str++;
end_ptr--;
}
}
bool isInDic(char* reversed)
{
FILE* words;
char singleLine[21];
words = fopen("words", "r");
if(words == NULL)
exit(EXIT_FAILURE);
while(fscanf(words, "%20s", singleLine) == 1)//the length of the string has to be 1 less than declared size for the newline character
{
//printf("singline: %s reversed: %s\n", singleLine, reversed);
if(strcmp(singleLine, reversed) == 0)//strcmp returns 0 if both cstrings are equal
return true;
}
fclose(words);
return false;
}
void addToEnd(node* head, char entry[21])
{
printf("hi");
//printf("\naddress of next %p\n", (void *)head->next);
while(head->next != NULL)//just reading head->next screws it up
head = head->next;
printf("in addToEnd 2\n");
node* last = (node*)malloc(sizeof(node));
printf("in addToEnd 3\n");
head->next = last;
printf("in addToEnd 4\n");
strcpy(last->entry, entry);
printf("in addToEnd 5\n");
last->next = NULL;
printf("in addToEnd 6\n");
}
unsigned int searchAndDestroy(node **head, char *entry)
{
unsigned int count = 0;
while(*head)
{
node *del;
if(strcmp((*head)->entry, entry))
{ //this node stays
head = &(*head)->next;
continue;
}
/* this node goes
at this point head MUST point to the pointer that points at the node to be deleted
*/
del = *head;
*head = (*head)->next;
free(del);
count++;
}
return count; //number of nodes deleted
}
void printList(node* head)
{
printf("\nprinting everything\n");
if(head != NULL)
{
while(head->next != NULL)
{
printf("%s", head->entry);
head = head->next;
}
printf("%s", head->entry);
}
}
The answers are correct that head is being set to null but I don't see where?
When you create head, you don't set head->next to NULL.
One of three things:
If head is NULL this code will crash at the line you mention.
If last->entry is defined as char* you need to say 'last->entry = strdup(entry)
If the sizeof last->entry is less than 21, your strcpy will overflow it which
will result in undefined behavior.
Ok, with your recent edit, I assert that head is null or garbage when you call this function the second time.
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 don't have much experience with c. Any help would be greatly appreciated.
my .c file
#include
#include
#include"animal.h"
#include
#include
/*returns a new node for the given value*/
struct Node * newNode (char *newValue)
{
struct Node * tree;
tree = (struct Node*)malloc(sizeof(struct Node));
tree -> value = newStr(newValue);
return tree;
}
/* returns a new string with value passed as an argument*/
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");
}
/*Read from a File and create a tree*/
struct Node * readATree(FILE * f)
{
char c;
char buffer[100];
struct Node * newTree;
c = fgetc(f);
if (c == 'A'){
fgets(buffer, 100, f);
newTree = newNode(buffer);
newTree -> left = NULL;
newTree -> right = NULL;
}
else{
fgets(buffer, 100, f);
newTree = newNode(newStr(buffer));
newTree->left = readATree(f);
newTree->right = (struct Node *) readAtree(f);
}
return newTree;
}
/*Write Tree to a File*/
void writeAFile(struct Node* tree, FILE * f)
{
char buffer[100];
strcpy(buffer, tree->value);
if(tree != 0){
if(tree->left == NULL && tree->right == NULL){
fputc((char)"A", f);
fputs(buffer,f);
} else{
fputc((char)"Q",f);
fputs(buffer,f);
writeAFile(tree->left, f);
writeAFile(tree->right,f);
}
}
}
/*The play should start from here*/
int main (){
struct Node* node;
struct Node* root;
char ans[100];
char q[100];
FILE * f;
f = fopen("animal.txt", "r+");
if(f != NULL)
readATree(f);
else{
node = newNode("Does it meow?");
node->right = NULL;
node->right->right=NULL;
node->left->left=NULL;
node->left=newNode("Cat");
root = node;
}
while(node->left != NULL && node->right != NULL){
printf(node->value);
scanf(ans);
if(ans[0] == (char)"Y" || ans[0] == (char)"y")
node = node->left;
else if(ans[0] == (char)"N" || ans[0] == (char)"n")
node = node->right;
else
printf("That is not a valid input.\n");
}
if(ans[0] == (char)"Y" || ans[0] == (char)"y")
printf("I win!");
else if(ans[0] == (char)"N" || ans[0] == (char)"n"){
printf("What is your animal");
scanf(ans);
printf("Please enter a yes or no question that is true about %s?\n", ans);
scanf(q);
node->right = newNode(q);
node->right->left = newNode(ans);
node->right->right = NULL;
}
writeAFile(root,f);
fclose(f);
return 0;
}
.h file
#include
struct Node {
char *value;
struct Node * left;
struct Node * right;
};
struct Node * newNode (char *newValue) ;
char * newStr (char * charBuffer);
struct Node * readATree(FILE * f);
void writeAFile(struct Node* tree, FILE * f);
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
}
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. :)
"+" 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.