Getting a segmentation fault. Can't figure out why - c

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

Related

Pointer to a structure unable to access values of 2D array

I am currently in the process of writing a program that acts as a circuit. I have a gate structure that takes a 2D char array in order to hold variable names, yet when I try to access these variable names stored in the array outside of the while loop, the content is empty.
typedef struct Gate
{
kind_t kind;
int size; // size of DECODER and MULTIPLEXER
char **params; // length determined by kind and size (CHANGED FROM INT TO CHAR)
// includes inputs and outputs, indicated by variable numbers
} Gate;
typedef struct Node
{
Gate *data;
struct Node *next;
} Node;
// Linked list of gates & attributes
while (fscanf(fp, "%16s", str) != EOF)
{
if (strcmp(str, "AND") == 0)
{
head = makeGate(fp, head, AND);
length++;
}
else if (strcmp(str, "OR") == 0)
{
head = makeGate(fp, head, OR);
length++;
}
else if (strcmp(str, "NAND") == 0)
{
head = makeGate(fp, head, NAND);
length++;
}
else if (strcmp(str, "NOR") == 0)
{
head = makeGate(fp, head, NOR);
length++;
}
else if (strcmp(str, "XOR") == 0)
{
head = makeGate(fp, head, XOR);
length++;
}
else if (strcmp(str, "NOT") == 0)
{
//head = makeGate(fp, head, NOT);
//length++;
}
else if (strcmp(str, "PASS") == 0)
{
//head = makeGate(fp, head, PASS);
//length++;
}
else if (strcmp(str, "DECODER") == 0)
{
//
}
else if (strcmp(str, "MULTIPLEXER") == 0)
{
//
}
printf("%s\n", head->data->params[2]);
}
// plugs in values to circuit
for (int i = 0; i < 3; i++)
{
printf("Stored string: %s\n", head->data->params[i]);
}
`
Node *makeGate(FILE *fp, Node *head, kind_t inGate)
{
char str[17];
Node *new_node = (Node *)malloc(sizeof(Node)); // Node of linkedlist that contains gate structure
new_node->data = (Gate *)malloc(sizeof(Gate)); // Gate structure that keeps information about a gate
new_node->next = head;
new_node->data->kind = inGate;
new_node->data->size = 3;
new_node->data->params = malloc(3 * sizeof(char*));
for (int i = 0; i < 3; i++)
{
new_node->data->params[i] = malloc(17 * sizeof(char));
}
fscanf(fp, "%16s", str);
new_node->data->params[0] = str;
fscanf(fp, "%16s", str);
new_node->data->params[1] = str;
fscanf(fp, "%16s", str);
new_node->data->params[2] = str;
return new_node;
}
`
The printf statement inside the while loop works perfectly fine and is there purely for testing, however the for loop that prints each value of the array is different and prints nothing.
I tried to fix this multiple times to no avail, I originally found this problem as I noticed that I had gotten memory leak, and when I freed where the memory leak should be, it throws that I am freeing a address that is not malloced.
My only thought is I am somehow losing/skipping a node, but I am out of ideas
The following does not copy data from str into the struct ( you'd need strcpy):
new_node->data->params[0] = str;
What it does is copy the address of str into each element. They all point to the same buffer/string. And, str goes out of scope when the function returns.
You can [and should] just scan into the struct directly.
So, change:
fscanf(fp, "%16s", str);
new_node->data->params[0] = str;
fscanf(fp, "%16s", str);
new_node->data->params[1] = str;
fscanf(fp, "%16s", str);
new_node->data->params[2] = str;
Into:
fscanf(fp,"%16s",new_node->data->params[0]);
fscanf(fp,"%16s",new_node->data->params[1]);
fscanf(fp,"%16s",new_node->data->params[2]);

Segmentation fault while using malloc

As an exercise I am trying to work on a Binary search tree!
I have created the code and it seems to run, but when I try to add a customer it crashes. After debugging the code I get a segmentation fault in line 82, where I try to allocate memory to root... Researching for a while I see that it is something related to memory, but can't figure what is going on with my code... Any suggestions about what is causing this failure when trying to allocate memory?
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define MAX_STRING 50
void flush();
struct customer {
char *name;
char *address;
char *email;
};
struct double_linked_list {
struct customer *data;
struct double_linked_list *previous;
struct double_linked_list *next;
};
struct double_linked_list *customers_head = 0;
struct BST_node {
struct double_linked_list *data;
struct BST_node *left;
struct BST_node *right;
};
struct BST_node *BST_email_root = 0;
struct BST_node *BST_find_customer(struct BST_node *root, char *email) {
if (root == NULL)
return NULL;
if (strcmp(email, root->data->data->email) == 0)
return root;
else {
if (strcmp(email, root->data->data->email) == -1)
return BST_find_customer(root->left, email);
else
return BST_find_customer(root->right, email);
}
}
void find_customer() {
char email[MAX_STRING];
struct double_linked_list *l;
struct BST_node *b;
printf("Give the email of the customer (up to %d characters) : ", MAX_STRING - 1);
gets(email);
b = BST_find_customer(BST_email_root, email);
if (b == 0)
printf("There is no customer with this email.\n");
else {
l = b->data;
printf("Customer found! \n");
printf("Name : %s\n", l->data->name);
printf("Address : %s\n", l->data->address);
printf("Email : %s\n", l->data->email);
}
}
struct BST_node *new_BST_node(struct BST_node *root, struct double_linked_list *l) {
if (root == NULL);
{
root = (struct BST_node *)malloc(sizeof(struct BST_node));
if (root == NULL) {
printf("Out of Memory!");
exit(1);
}
root->data = l;
root->left = NULL;
root->right = NULL;
}
if (strcmp(l->data->email, root->data->data->email) == -1)
root->left = new_BST_node(root->left, l);
else
root->right = new_BST_node(root->right, l);
return root;
};
struct double_linked_list *new_customer() {
char name[MAX_STRING], address[MAX_STRING], email[MAX_STRING];
struct BST_node *b;
struct double_linked_list *l;
struct customer *c;
printf("\nADDING NEW CUSTOMER\n=\n\n");
printf("Give name (up to %d characters): ", MAX_STRING - 1);
gets(name);
printf("Give address (up to %d characters): ", MAX_STRING - 1);
gets(address);
printf("Give email (up to %d characters): ", MAX_STRING - 1);
gets(email);
b = BST_find_customer(BST_email_root, email);
if (b) {
printf("Duplicate email. Customer aborted.\n");
return 0;
}
c = (struct customer *)malloc(sizeof(struct customer));
if (c == 0) {
printf("Not enough memory.\n");
return 0;
}
c->name = strdup(name); // check for memory allocation problem
if (c->name == 0)
return 0;
c->address = strdup(address); // check for memory allocation problem
if (c->address == 0)
return 0;
c->email = strdup(email); // check for memory allocation problem
if (c->email == 0)
return 0;
l = (struct double_linked_list*)malloc(sizeof(struct double_linked_list));
if (l == 0) {
printf("Not enough memory.\n");
free(c->name);
free(c->address);
free(c->email);
free(c);
return 0;
}
l->data = c;
l->previous = 0;
l->next = customers_head;
if (customers_head)
customers_head->previous = l;
customers_head = l;
BST_email_root = new_BST_node(BST_email_root, l);
return l;
}
void displaymenu() {
printf("\n\n");
printf("1. New customer\n");
printf("2. Find customer using email\n");
printf("0. Exit\n\n");
printf("Give a choice (0-6) : ");
}
void flush() {
char ch;
while ((ch = getchar()) != '\n' && ch != EOF);
}
int main() {
int choice;
do {
displaymenu();
scanf("%d", &choice);
flush();
switch (choice) {
case 1:
new_customer();
break;
case 2:
find_customer();
break;
}
} while (choice != 0);
return 0;
}
Codeblocks debugger gives the following information
Active debugger config: GDB/CDB debugger:Default
Building to ensure sources are up-to-date
Selecting target:
Debug
Adding source dir: C:\debug\
Adding source dir: C:\debug\
Adding file: C:\debug\bin\Debug\debug.exe
Changing directory to: C:/debug/.
Set variable: PATH=.;C:\Program Files\CodeBlocks\MinGW\bin;C:\Program Files\CodeBlocks\MinGW;C:\Windows\System32;C:\Windows;C:\Windows\System32\wbem;C:\Windows\System32\WindowsPowerShell\v1.0;C:\Program Files\ATI Technologies\ATI.ACE\Core-Static;C:\Users\baskon\AppData\Local\Microsoft\WindowsApps
Starting debugger: C:\Program Files\CodeBlocks\MINGW\bin\gdb.exe -nx -fullname -quiet -args C:/debug/bin/Debug/debug.exe
done
Registered new type: wxString
Registered new type: STL String
Registered new type: STL Vector
Setting breakpoints
Debugger name and version: GNU gdb (GDB) 7.6.1
Child process PID: 5908
Program received signal SIGSEGV, Segmentation fault.
In ?? () ()
9 0x00401480 in new_BST_node (root=0x0, l=0xbe0ec8) at C:\debug\main.c:82
C:\debug\main.c:82:1907:beg:0x401480
At C:\debug\main.c:82
9 0x00401480 in new_BST_node (root=0x0, l=0xbe0ec8) at C:\debug\main.c:82
C:\debug\main.c:82:1907:beg:0x401480
The call stack is the following
There are multiple problems in your code:
You have a classic bug here:
struct BST_node *new_BST_node(struct BST_node *root, struct double_linked_list *l) {
if (root == NULL);
{
root = (struct BST_node *)malloc(sizeof(struct BST_node));
The ; at the end of the if statement line is parsed as an empty statement. The subsequent block, introduced by the { will always be executed.
You can avoid this kind of silly bug by always using braces for your compound statements and placing them on the same line as the beginning of the statement, not on the next line. This is close to the original K&R style used by the creators of the C language more than 40 years ago.
The type for variable ch in function flush should be int to allow proper distinction of all values returned by getc(): all values of unsigned char plus the special value EOF:
void flush(void) {
int ch;
while ((ch = getchar()) != EOF && ch != '\n') {
continue;
}
}
Note that you should make the empty statement more explicit as I did above, to avoid confusion and bugs such as the previous one.
You should not use the obsolete unsafe function gets(): Use fgets() and strip the trailing newline with strcspn().
When comparing strings with strcmp(), you should only rely on the sign of the return value. In functions BST_find_customer() and new_BST_node(), you compare with -1: this is unreliable. Use if (strcmp(email, root->data->data->email) < 0) instead.
In function new_BST_node(), You do not return root when you create a new node in the tree. Here is a corrected version:
struct BST_node *new_BST_node(struct BST_node *root, struct double_linked_list *l) {
if (root == NULL) {
root = malloc(sizeof(*root));
if (root == NULL) {
printf("Out of Memory!");
exit(1);
}
root->data = l;
root->left = NULL;
root->right = NULL;
return root;
}
if (strcmp(l->data->email, root->data->data->email) < 0) {
root->left = new_BST_node(root->left, l);
} else {
root->right = new_BST_node(root->right, l);
}
return root;
}
Note that this is causing your bug as you probably have an infinite recursion here.
Finally a couple pieces of advice:
use NULL instead of 0 when comparing pointers to the null pointer. It is more readable.
avoid naming a variable l as this name is graphically too close to 1 with the fixed pitch fonts used in programming environments. Sometimes it is almost indistinguishable.
Ok, so after testing everything i found out what is wrong however i can't figure out why.. Any Suggestions??
I think that strcmp returns values of either 0 or -1 or 1.
But there was the problem, if i didn't define exactly if strcmp ==1 or if strcmp ==-1 ...i had an infinite loop as it seems (i used a printf command to see what is going on, and i discovered the bug..)
By changing
struct BST_node *new_BST_node(struct BST_node *root, struct double_linked_list *l)
{
if (root==NULL)
{
root = (struct BST_node *) malloc (sizeof(struct BST_node ));
if (root==NULL)
{
printf("Out of Memory!");
exit(1);
}
root->data=l;
root->left=NULL;
root->right=NULL;
}
if (strcmp(l->data->email, root->data->data->email) == -1)
root->left =new_BST_node(root->left,l);
else
root->right =new_BST_node(root->right,l);
return root;
};
to
struct BST_node *new_BST_node(struct BST_node *root, struct double_linked_list *l)
{
if (root==NULL)
{
root= (struct BST_node *)malloc(sizeof(struct BST_node ));
if (root==NULL)
{
printf("Out of Memory!");
exit(1);
}
root->data=l;
root->left=NULL;
root->right=NULL;
}
if ((strcmp(l->data->email, root->data->data->email))==-1)
root->left =new_BST_node(root->left,l);
else if ((strcmp(l->data->email, root->data->data->email)) ==1)
root->right =new_BST_node(root->right,l);
return root;
};
everything works fine..
But why didnt the other code work? I am pretty sure it is the same...

Can't printf contents of a single-linked-list of strings

I have written this piece of code here and I have linked it alright with a couple of other functions and a main and it is working no problem and compiling without warnings (I am using the gcc compiler).
I use an array of pointers (archive.products[]) as an entrance point to multiple lists of strings. I'm still at the beginning so the lists have only one node each.
The problem I've got is that I can't get the function lprintf to show on screen the components of the one-node lists of strings I have created. Note that the printf located inside the push function prints alright. So I know that push is doing it's job...
If anyone has any idea about what might I be doing wrong please drop a reply below.
Thank-you in advance!
#define line_length 61
#define max_products 10
struct terminal_list {
char terminal[line_length];
struct terminal_list *next;
}*newnode, *browser;
typedef struct terminal_list tlst;
struct hilevel_data {
char category[line_length];
tlst *products[max_products];
};
typedef struct hilevel_data hld;
void import_terms(FILE *fp, hld archive){
char buffer[line_length];
char filter_t[3] = "}\n";
int i = 0, j = 0;
while (!feof(fp)) {
fgets(buffer, line_length, fp);
if (strcmp(buffer, filter_t) == 0) {
return;
}
head_initiator(archive, i);
push(buffer,archive, i);
lprintf();
i++;
}
}
void head_initiator(hld archive, int i){
browser = NULL;
archive.products[i] = NULL;
}
void push(char buffer[],hld archive, int i){
newnode = (tlst *)malloc(sizeof(tlst));
strcpy(newnode->terminal, buffer);
// printf("%s", newnode->terminal);
archive.products[i] = browser;
newnode->next = browser;
browser = newnode;
}
void lprintf(){
tlst *p;
p = browser;
if (p = NULL){
printf("empty\n");
}
while(p!=NULL){
printf("%s\n", p->terminal);
p=p->next;
}
}
On : void lprintf()
if (p = NULL)
should be
if (p == NULL)
if (p = NULL){
printf("empty\n");
}
I think you mean
if (p == NULL){
printf("empty\n");
}
You're effectively emptying the list with p = NULL.

Can't pinpoint Segmentation fault [duplicate]

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

Seg Fault in Knowledge Tree

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.

Resources