c: program execution problem - c

I wrote this code and compiled it,
#include <windows.h>
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
// Data Structures
typedef struct process{
char jobName;
int arrivalTime;
int execTime;
struct process *next;
} P;
typedef struct result{
char Name;
struct result *next;
} result;
// End of Data Structures
int quantum;
int jobCounts=0;
int ResponseTime=0;
double timeEsp=0;
// Function Prototypes
int gettimeofday(struct timeval *tp, void * tzp);
void add_to_process_list(P **List,P *data);
void add_to_result_list(result **List,char name);
P *readData(char* fileName);
void writeData(result *res,char *out);
P *removeFromList(P **head,P **El);
int jobCount(P *head);
double get_time(void);
// End of Function Prototypes
int main(int argc,char *argv[]){
P *pList=NULL,*tmpNode=NULL;
result *RR_result=NULL,*JR=NULL;
double start, stop;
int counter=0;
printf("Reading Data ... ");
pList=readData(argv[1]);
printf("Complete\n");
jobCounts=jobCount(pList);
start = get_time();
printf("Algorithm Started ...\n");
if(pList!=NULL){
tmpNode=pList;
while(tmpNode!=NULL){
if(tmpNode->arrivalTime<=counter){
JR=(result *)malloc(sizeof(result *));
printf("Giving Quantum to %c\n",tmpNode->jobName);
Sleep(quantum*1000); //simulate process time
add_to_result_list(&RR_result,tmpNode->jobName);
tmpNode->execTime-=quantum;
if(tmpNode->execTime==0){
ResponseTime+=((get_time()-start)-tmpNode->arrivalTime);
tmpNode=removeFromList(&pList,&tmpNode);
}else
tmpNode=tmpNode->next;
counter++;
}else
tmpNode=tmpNode->next;
}
printf("Algorithm Finished.\n");
stop= get_time();
timeEsp=(stop-start);
printf("Writing data ... ");
writeData(RR_result,argv[2]);
printf("Completed.\n");
return 0;
}else{
return 1;
}
}
void add_to_process_list(P **List,P *data){
P *new=malloc(sizeof(P));
new->arrivalTime=data->arrivalTime;
new->execTime=data->execTime;
new->jobName=data->jobName;
if((*List)==NULL){
new->next=new;
*List=new;
}else{
P *tmp;
tmp=*List;
while(tmp->next!=(*List)) tmp=tmp->next;
tmp->next=new;
new->next=*List;
}
}
void add_to_result_list(result **List,char name){
result *new=malloc(sizeof(result));
new->Name=name;
new->next=NULL;
if(*List==NULL){
*List=new;
}else{
result *tmp;
tmp=*List;
while(tmp->next!=NULL) tmp=tmp->next;
tmp->next=new;
}
}
P *readData(char* fileName){
P *head=NULL,*cur=NULL;
char Name[20],tmp[255];
int AT,ET;
FILE *iF;
if((iF=fopen(fileName,"r"))>0){
fgets(tmp,255,iF);
sscanf(tmp,"Interval:%d\n",&quantum);
fgets(tmp,255,iF); //waste
while(!feof(iF) && fgets(tmp,255,iF)){
sscanf(tmp,"%20c %20d %20d",Name,&AT,&ET);
cur=(P *)malloc(sizeof(P *));
cur->jobName=Name[0];
cur->arrivalTime=AT;
cur->execTime=ET;
add_to_process_list(&head,cur);
}
fclose(iF);
return head;
}else{
printf("Fatal error:\n\tError openning input file.\n");
return NULL;
}
}
void writeData(result * res ,char *out){
result *tmp=res;
FILE *oF;
int tmpCounter=1;
double throughput=jobCounts/timeEsp;
double RR=ResponseTime/jobCounts;
if((oF=fopen(out,"w"))>0){
fprintf(oF,"%-15s %-15s\n","Job Name","Execution Time");
while(tmp!=NULL){
if(tmp->next!=NULL && tmp->Name==tmp->next->Name)
tmpCounter++;
else{
fprintf(oF,"%-15c %-15d\n",tmp->Name,tmpCounter*quantum);
tmpCounter=1;
}
tmp=tmp->next;
}
fprintf(oF,"Response Time: %0.2f\n",RR);
fprintf(oF,"Throghput: %0.2f\n",throughput);
fclose(oF);
}else{
printf("Fatal error:\n\tError openning output file.\n");
}
}
P *removeFromList(P **head,P **El){
P *tmp=*head;
if((*El)->next==*El){
free(*El);
return NULL;
}else{
while(tmp->next!=NULL && tmp->next!=*El) tmp=tmp->next;
tmp->next=tmp->next->next;
free(*El);
return tmp->next;
}
}
int jobCount(P *head){
P *tmp=head;
int count=1;
if(tmp->next==tmp){
return 1;
}
while(tmp->next!=head) {
tmp=tmp->next;
count++;
}
return count;
}
double get_time(void){
struct timeval stime;
gettimeofday (&stime, (struct timezone*)0);
return (stime.tv_sec+((double)stime.tv_usec)/1000000);
}
it worked correctly but when I chenged it to the code bellow (removing program arguments and use static file names) I can't run program and to pauses on reading data ! (the strange thing is when I run second code with argument (I mean just pass argument in execution) it works!!
#include <windows.h>
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
// Data Structures
typedef struct process{
char jobName;
int arrivalTime;
int execTime;
struct process *next;
} P;
typedef struct result{
char Name;
struct result *next;
} result;
// End of Data Structures
int quantum;
int jobCounts=0;
int ResponseTime=0;
double timeEsp=0;
// Function Prototypes
int gettimeofday(struct timeval *tp, void * tzp);
void add_to_process_list(P **List,P *data);
void add_to_result_list(result **List,char name);
P *readData(char* fileName);
void writeData(result *res,char *out);
P *removeFromList(P **head,P **El);
int jobCount(P *head);
double get_time(void);
// End of Function Prototypes
int main(){
P *pList=NULL,*tmpNode=NULL;
result *RR_result=NULL,*JR=NULL;
double start, stop;
int counter=0;
char *in="input.txt";
char *out="output.txt";
printf("Reading Data ... ");
pList=readData(in);
printf("Complete\n");
jobCounts=jobCount(pList);
start = get_time();
printf("Algorithm Started ...\n");
if(pList!=NULL){
tmpNode=pList;
while(tmpNode!=NULL){
if(tmpNode->arrivalTime<=counter){
JR=(result *)malloc(sizeof(result *));
printf("Giving Quantum to %c\n",tmpNode->jobName);
Sleep(quantum*1000); //simulate process time
add_to_result_list(&RR_result,tmpNode->jobName);
tmpNode->execTime-=quantum;
if(tmpNode->execTime==0){
ResponseTime+=((get_time()-start)-tmpNode->arrivalTime);
tmpNode=removeFromList(&pList,&tmpNode);
}else
tmpNode=tmpNode->next;
counter++;
}else
tmpNode=tmpNode->next;
}
printf("Algorithm Finished.\n");
stop= get_time();
timeEsp=(stop-start);
printf("Writing data ... ");
writeData(RR_result,out);
printf("Completed.\n");
return 0;
}else{
return 1;
}
}
void add_to_process_list(P **List,P *data){
P *new=malloc(sizeof(P));
new->arrivalTime=data->arrivalTime;
new->execTime=data->execTime;
new->jobName=data->jobName;
if((*List)==NULL){
new->next=new;
*List=new;
}else{
P *tmp;
tmp=*List;
while(tmp->next!=(*List)) tmp=tmp->next;
tmp->next=new;
new->next=*List;
}
}
void add_to_result_list(result **List,char name){
result *new=malloc(sizeof(result));
new->Name=name;
new->next=NULL;
if(*List==NULL){
*List=new;
}else{
result *tmp;
tmp=*List;
while(tmp->next!=NULL) tmp=tmp->next;
tmp->next=new;
}
}
P *readData(char* fileName){
P *head=NULL,*cur=NULL;
char Name[20],tmp[255];
int AT,ET;
FILE *iF;
if((iF=fopen(fileName,"r"))>0){
fgets(tmp,255,iF);
sscanf(tmp,"Interval:%d\n",&quantum);
fgets(tmp,255,iF); //waste
while(!feof(iF) && fgets(tmp,255,iF)){
sscanf(tmp,"%20c %20d %20d",Name,&AT,&ET);
cur=(P *)malloc(sizeof(P *));
cur->jobName=Name[0];
cur->arrivalTime=AT;
cur->execTime=ET;
add_to_process_list(&head,cur);
}
fclose(iF);
return head;
}else{
printf("Fatal error:\n\tError openning input file.\n");
return NULL;
}
}
void writeData(result * res ,char *out){
result *tmp=res;
FILE *oF;
int tmpCounter=1;
double throughput=jobCounts/timeEsp;
double RR=ResponseTime/jobCounts;
if((oF=fopen(out,"w"))>0){
fprintf(oF,"%-15s %-15s\n","Job Name","Execution Time");
while(tmp!=NULL){
if(tmp->next!=NULL && tmp->Name==tmp->next->Name)
tmpCounter++;
else{
fprintf(oF,"%-15c %-15d\n",tmp->Name,tmpCounter*quantum);
tmpCounter=1;
}
tmp=tmp->next;
}
fprintf(oF,"Response Time: %0.2f\n",RR);
fprintf(oF,"Throghput: %0.2f\n",throughput);
fclose(oF);
}else{
printf("Fatal error:\n\tError openning output file.\n");
}
}
P *removeFromList(P **head,P **El){
P *tmp=*head;
if((*El)->next==*El){
free(*El);
return NULL;
}else{
while(tmp->next!=NULL && tmp->next!=*El) tmp=tmp->next;
tmp->next=tmp->next->next;
free(*El);
return tmp->next;
}
}
int jobCount(P *head){
P *tmp=head;
int count=1;
if(tmp->next==tmp){
return 1;
}
while(tmp->next!=head) {
tmp=tmp->next;
count++;
}
return count;
}
double get_time(void){
struct timeval stime;
gettimeofday (&stime, (struct timezone*)0);
return (stime.tv_sec+((double)stime.tv_usec)/1000000);
}
What's the problem? is it buffer overflow?!
Thanks

There appears to be at least one overflow. The following allocation is only allocating 4 bytes (in a 32-bit system):
cur=(P *)malloc(sizeof(P *));
It should probably be:
cur=(P *)malloc(sizeof(P));

Related

How to convert a decimal to binary in C programming using stack

I'm trying a C programming code which will convert a decimal number into binary number and the binary values will be stored in a stack
According to my code, when running it shows some error responses. When trying to display the binary number using peek method, the application runs without an end.
#include<stdio.h>
#include<stdlib.h>
#define MAX 50
typedef enum{FALSE, TRUE} boolean;
typedef struct stack{
int top;
int a[MAX];
} stack;
void CreateStack(stack *s){
s->top = -1;
}
boolean isEmpty(stack *s){
return (s->top == -1);
}
boolean isFull(stack *s){
return(s->top == MAX - 1);
}
void push(stack *s, int data){
if(isFull(s)){
exit(1);
}
else{
s->top = s->top + 1;
s->a[s->top] = data;
}
}
int pop(stack *s){
if(isEmpty(s)){
exit(1);
}
else{
return s->a[s->top];
s->top = s->top - 1;
}
}
int peek(stack *s){
return s->a[s->top];
}
void binary(stack *s, int num){
int n;
while(num != 0){
if(!isFull(s)){
n = num % 2;
push(s,n);
num = num / 2;
}
else{
exit(1);
}
}
}
void main() {
stack s;
CreateStack(&s);
int num,n;
printf("Enter the decimal number: ");
scanf("%d",&num);
binary(&s,num);
printf("Top = %d\n",peek(&s));
while(!isEmpty(&s)){
printf("%d ",pop(&s));
}
}
pop() contains dead code — it returns value but top decrement placed after the return operator and will be newer reached.
int pop(stack *s){
if(isEmpty(s)){
exit(1);
}
else{
return s->a[s->top];
s->top = s->top - 1; // <------------
}
}
Change it in following manner:
int pop(stack *s){
if(isEmpty(s)){
exit(1);
}
else{
int temp = s->a[s->top];
s->top = s->top - 1;
return temp;
}
}
p.s. As for me, else keyword can be omitted here but it is taste issue:
int pop(stack *s) {
int temp;
if(isEmpty(s))
exit(1);
temp = s->a[s->top];
s->top = s->top - 1;
return temp;
}

Error: Syntax error before 'struct'

My code is basically functions used for making/using a stack. I've tried almost everything, but I don't know why my program is displaying this error:
Error: Syntax error before 'struct'
#include "stack.h"
#include <stdio.h>
#include <stdlib.h>
#define CAPACITY 128
struct stack_struct {
ElemType items[CAPACITY];
int top;
};
StackPtr stk_create(){
StackPtr s = malloc(sizeof(struct stack_struct));
s->top = -1; // stack initially empty
return s;
}
// TODO
StackPtr stk_clone(StackPtr s) {
return NULL; // temporary placeholder
}
void stk_free(StackPtr s) {
free(s);
}
int stk_push(StackPtr s, ElemType val){
if(s->top == CAPACITY - 1)
struct stack_struct * temp;
temp = (struct stack_struct*)malloc(sizeof(struct stack_struct));
s->top++;
s->items[s->top] = val;
return 1;
}
ElemType stk_pop(StackPtr s){
if(s->top == -1)
abort(); // library function which terminates program!!!
s->top--;
return s->items[s->top+1];
}
int stk_is_full(StackPtr s){
return s->top == CAPACITY-1;
}
int stk_is_empty(StackPtr s){
return s->top == -1;
}
int stk_size(StackPtr s) {
return s->top+1;
}
void stk_clear(StackPtr s){
s->top = -1;
}
void stk_print(StackPtr s) {
int i;
printf("\n----TOP-----\n");
for(i=s->top; i>=0; i--) {
printf(FORMAT_STRING, s->items[i]);
}
printf("---BOTTOM---\n");
}
int main() {
StackPtr sptr;
sptr = stk_create();
stk_push(sptr, 1.7);
stk_push(sptr, 3.14);
stk_print(sptr);
stk_pop(sptr);
stk_print(sptr);
stk_free(sptr);
}
As I could see, function stack_push should look like this
int stk_push(StackPtr s, ElemType val){
if(stk_is_full(s))
return -1; // stack already full, we couldn't push new elem
s->top++;
s->items[s->top] = val;
return 1;
}
I think error in this line (line 35 in your source code):
struct stack_struct * temp;
. Let's try
typedef struct stack_struct * temp;
or change declare struct
struct stack_struct {
ElemType items[CAPACITY];
int top;} stack;
and then call
stack* temp;
in line 35.

Traversing and printing a queue in C behaves differently when input is given by the user

I apologise if this concept has been explained on SOF before! I believe my case is slightly different and couldn't find a similar question in the website.
Here's the problem:
I'm trying to store char arrays (strings) in a Queue structure that I'm trying to implement.
The structure and its functions seem to work fine when I hardcode the data myself like this:
#include "Time.h"
#include <unistd.h>
int main(void){
struct Queue* q = CreateQueue();
Enqueue(q, "element1");
Enqueue(q, "element2");
Enqueue(q, "element3");
Enqueue(q, "element4");
PrintAll(q->first); // this outputs all elements and the time they've been in the queue.
return 0;
}
The output is as expected, a list of all 4 elements.
However, as soon as I put a simple menu together, to capture the data from the user instead of it being hardcoded as above, the PrintAll() function outputs a duplicate of the very last element enqueued. You also notice that I am timing each node to keep a track on when it was added to the queue and that seem to work fine. Although the ouput shows the last element entered duplicated N times (N being the size of the queue) the timer seems to show correctly for each node!
I am suspecting it's to do with the stdin stream that is not being cleaned but I thought I handled that with a block of code that is shown in main() function.
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
int main(void){
char name[31];
char c;
int option;
int ch;
struct Queue* q = CreateQueue();
do
{
printf("\n 1. Add a an element to the queue");
printf("\n 2. Print all elements");
printf("\n 0. Exit");
printf("\n Please select an option");
while(scanf("%d", &option)!=1){
puts("Value non good");
ch=getchar();
while(ch!=EOF && ch!='\n'){
ch=getchar();
}
}
switch(option)
{
case 1:
{
ch=getchar();
while(ch!=EOF && ch!='\n')
{
ch=getchar();
}
printf("Please enter the name of the element.\n ");
fgets(name,30,stdin);
Enqueue(q, name);
PrintAll(q->first);
break;
}
case 2:
{
PrintAll(q->last);
break;
}
default:
return 0;
}
}while(option != 0);
return 0;
}
Can anybody please shed light on the problem ? I would appreciate it.
here's the rest of the code:
Time.c:
#include "Time.h"
struct Queue* CreateQueue()
{
struct Queue* q = malloc(sizeof(struct Queue));
q->first = NULL;
q->last = NULL;
q->size = 0;
return q;
}
void Enqueue(struct Queue* queue, char* string)
{
struct Node* newNode = malloc(sizeof(struct Node));
newNode->next = NULL;
newNode->student = string;
newNode->start_time = time(0);
if(queue->size == 0)
{
queue->first = newNode;
}
else
{
queue->last->next = newNode;
}
queue->last = newNode;
queue->size = queue->size + 1;
}
char* Dequeue(struct Queue* queue)
{
if (queue->size < 0)
{
exit(0);
}
char* toBeRemoved = queue->first->student;
struct Node* oldNode = queue->first;
queue->first = oldNode->next;
queue->size = queue->size - 1;
if(queue->size == 0)
{
queue->last = NULL;
}
free(oldNode);
return toBeRemoved;
}
int IsEmpty(struct Queue *q)
{
return q->size == 0;
}
char* Peek(struct Queue *q)
{
return q->first->student;
}
void PrintOne(struct Node *node)
{
if(node !=NULL)
{
int elapsed = ElapsedTime(node);
printTime(elapsed, node->student);
//printf("%s\n", node->student);
}
}
void PrintAll(struct Node* node)
{
if (node !=NULL)
{
PrintAll(node->next);
PrintOne(node);
}
}
// returns the waiting time for a student node.
int ElapsedTime(struct Node* node)
{
int elapsed;
time_t stop_time;
stop_time = time(NULL);
elapsed = difftime( stop_time , node->start_time );
return elapsed;
}
void printTime(int elapsed, char* student_name)
{
printf("%s : waiting for ", student_name);
int minutes_or_hours = 0; //Stores a zero to indicate that it is not neccesary to print minutes or hours.
//Stores a one to indicate that hours and/or minutes have been printed.
if( (elapsed / 3600) >= 1)
{
int hours = elapsed/3600;
if(hours == 1)
{
printf("1 hour, ");
}
else
{
printf("%d hours, ", hours);
}
elapsed = elapsed - (hours*3600);
minutes_or_hours = 1;
}
if( (elapsed / 60) >= 1)
{
int minutes = elapsed/60;
if(minutes == 1)
{
printf("1 minute, ");
}
else
{
printf("%d minutes, ", minutes);
}
minutes_or_hours = 1;
elapsed = elapsed - (minutes*60);
}
if(minutes_or_hours == 1)
{
printf("and ");
}
printf("%d seconds\n", elapsed);
}
Time.h:
#ifndef TIME_H_
#define TIME_H_
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
struct Node
{
time_t start_time;
struct Node* next;
char* student;
};
struct Queue
{
int size;
struct Node* first;
struct Node* last;
};
struct Queue* CreateQueue();
void Enqueue(struct Queue* , char* );
char* Dequeue(struct Queue* );
int IsEmpty(struct Queue *);
char* Peek(struct Queue *);
void PrintOne(struct Node *);
void PrintAll(struct Node *);
int ElapsedTime(struct Node* );
void printTime(int , char* );
#endif /* TIME_H_ */
In the function Enqueue() you have only copied the string pointer to your structure. In your first case that works, because all the four strings have different pointers to string literals. But in your second example, you are storing the pointer of your data entry name, and the contents of this string change with each entry. Each structure store the same pointer, so all point to the most recent string you typed in. If your struct stored the actual string, it would work (but you need to be careful with string lengths).
struct Node
{
time_t start_time;
struct Node* next;
char student[31];
};
void Enqueue(struct Queue* queue, char* string)
{
...
strncpy (newNode->student, 30, string);
...
}

Binary Search Tree Madness

I have to write an implementation of a binary search tree that can handle a library's stock. It reads a text file with all the books and add the books to the tree in alphabetic order. I have been fighting with the Insertar() function code for DAYS and i can't make it work properly, it basically receives a pointer for the root of the tree along all the data related to the book. If the root is NULL, then it inits a node with all the values entered in the function and asings the memory direction to the null node. The problem is, its doing it locally and in the end it doesnt assigns it. Can somebody help me correct that specific function please?
Functions and Structs:
nodoArbol: The node
ArbolBin: Binary Tree, it has a pointer to a root node and an int with the number of elements
InitNodo: Inits the node, returns pointer to node
Raiz: Returns a pointer to the root of a Binary Tree
Clear,Clear_Aux: Clears a Tree
Ingresar: Insert() function and the source of the problem
Imprimir: rints the elements of a node.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
typedef struct nodoArbol {
char nombre[51],autor[51];
int valor,stock,anno;
struct nodoArbol *der;
struct nodoArbol *izq;
} tNodoArbol;
typedef struct {
tNodoArbol *root;
int n;
} ArbolBin;
tNodoArbol* InitNodo(char *nombre,char *autor, int stock, int valor, int anno){
tNodoArbol *p;
p= (tNodoArbol*)malloc(sizeof(tNodoArbol));
strcpy(p->nombre, nombre);
strcpy(p->autor, autor);
p->stock = stock;
p->anno = anno;
p->valor = valor;
p->izq = NULL;
p->der = NULL;
return p;
}
tNodoArbol* Raiz(ArbolBin p){
return (&p)-> root;
}
void Init(ArbolBin *p){
p->root = NULL;
p->n = 0;
}
void clear_aux(tNodoArbol *nodo){
if (nodo == NULL){
return;
}
clear_aux(nodo->izq);
clear_aux(nodo->der);
free((void *) nodo);
}
void Clear(ArbolBin *p){
clear_aux(p->root);
p->root = NULL;
p->n = 0;
}
void Insertar (tNodoArbol *nodo, char *nombre,char *autor, int stock, int valor, int anno){
if (nodo == NULL){
nodo = (InitNodo(nombre,autor,stock,valor,anno));
}
else{
int result;
result = strcmp(nodo->nombre,nombre);
if (result>0){
Insertar (nodo->der, nombre,autor,stock,valor,anno);
}
else if (result<0){
Insertar (nodo->izq, nombre,autor,stock,valor,anno);
}
}
}
void Imprimir(tNodoArbol *nodo){
printf("Nombre:%s \n",nodo->nombre);
printf("Autor:%s \n",nodo->autor);
printf("Stock:%d \n",nodo->stock);
printf("Valor:%d \n",nodo->valor);
printf("anno:%d \n",nodo->anno);
}
int main(){
char a[50]= "holi",b[50] ="asdasdasd";
ArbolBin Tree;
tNodoArbol *Root;
Init(&Tree);
Root = Raiz(Tree);
Insertar(Root,a,b,2,1000,2014);
Imprimir(Root);
return 0;
}
tNodoArbol *Root;
Insertar(Root,a,b,2,1000,2014);
void Insertar (tNodoArbol *nodo, char *nombre,char *autor, int stock, int valor, int anno){
if (nodo == NULL){
nodo = (InitNodo(nombre,autor,stock,valor,anno));
}
else{
int result;
result = strcmp(nodo->nombre,nombre);
if (result>0){
Insertar (nodo->der, nombre,autor,stock,valor,anno);/*nodo just a pointer,node->der is illeagl*/
}
else if (result<0){
Insertar (nodo->izq, nombre,autor,stock,valor,anno);/*the same error */
}
}
}
-----------------------------------------------------------------------------------------
your declaration a pointer, you want through the Insertar() change the Root, you need use
Insertar(&Root,a,b,2,1000,2014), because the Root in the Insertar() is not the Root in the main() ,they just have the same value,we just copy the value of Root(main) to Root(Insertar).
---------------------------------------------------------------------------------------
void Insertar (tNodoArbol **nodo, char *nombre,char *autor, int stock, int valor, int anno){
if (*nodo == NULL){
*nodo = (InitNodo(nombre,autor,stock,valor,anno));
}
else{
int result;
result = strcmp((*nodo)->nombre,nombre);
if (result>0){
Insertar ((*nodo)->der, nombre,autor,stock,valor,anno);
}
else if (result<0){
Insertar ((*nodo)->izq, nombre,autor,stock,valor,anno);
}
}
}

i got some issues reading words from a .txt file in C

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define WORD_LENGHT 30
typedef struct numnode
{
char* dataPtr;
struct numnode* next;
} NUMNODE;
typedef struct num
{
NUMNODE* head;
} NUM;
//////
//////
//////
int main()
{
char *wp;
char word[80];
int total=0;
FILE *test= fopen("book.txt", "r");
while (fscanf (test, "%s",word) == 1)
{
//printf("%s\n",word); //counting how many words in a book.txt
total++;
}
if (total==0)
{
printf("File not found\n"); //if no word, then return
return;
}
NUM* dic;
dic=(NUM*)malloc(sizeof(NUM)*total);
NUMNODE* temp;
temp=dic->head;
FILE*file = fopen("book.txt", "r");
while(!feof(file))
{
wp=malloc(100);
printf("test1\n");
fscanf(file,"%s",wp);
strcpy(temp->dataPtr,wp); //strcpy is the error part
printf("test2\n");
temp=temp->next;
}
return;
}
this c code read word by word from book.txt and put them to linked
list. i got some issues with !feof(file) part.Couldnt figure out what
to do.i think strcpy in this loop is the reason of this issue.im
waiting for your helps :3
Error is because the struct member dataPtr is a pointer, not an array. So the strcpy call
strcpy(temp->dataPtr,wp);
is wrong because it accesses illegal memory invoking undefined behaviour. What you need is
typedef struct numnode
{
char dataPtr[100]; // dataPtr changed to an array type
struct numnode* next;
} NUMNODE;
Please note that dataPtr must be at least the size of the buffer pointed to by wp.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define WORD_LENGHT 30
typedef struct numnode {
char* dataPtr;
struct numnode* next;
} NUMNODE;
typedef struct num {
NUMNODE* head;
} NUM;
int main(){
NUM dic = { NULL };
char word[WORD_LENGHT];
int total=0;//num of word
FILE *file= fopen("book.txt", "r");
NUMNODE *curr = NULL, *temp;
while (fscanf(file, "%29s", word) == 1) {
temp = malloc(sizeof(*temp));
temp->dataPtr = malloc(strlen(word) + 1);
temp->next = NULL;,
strcpy(temp->dataPtr, word);
if(curr){
curr = curr->next = temp;
} else {
dic.head = curr = temp;
}
++total;
}
if (total==0){
printf("File does not has word\n");
return;
}
//test print
printf("%d\n", total);
if(total>1){
printf("%s\n", dic.head->dataPtr);
printf("%s\n", dic.head->next->dataPtr);
}
//do something
return;
}
,

Resources