i want to reverse a sentence using stack in c.
eg. how are you => you are how.
i have written the following program
#include<stdio.h>
#include<conio.h>
struct rev
{
char *var;
struct rev *next;
};
struct rev *top=NULL;
struct rev *temp,*test;
main()
{
int start, j = 0;
char *p="Hi, How are you? Hope everything is fine";
char *s;
char *t;
*t = '\0';
s = p;
while(1) {
if(*p == ' '|| *p == '\0') {
printf("Inside if \n");
*(t + j) = '\0';
printf("This is t %s\n",t);
if(top == NULL) {
temp = (struct rev *)malloc(sizeof(struct rev));
temp->next = NULL;
temp->var=t;
top = temp;
} else {
temp = (struct rev *)malloc(sizeof(struct rev));
printf("This is going in stack %s\n", t);
temp->var = t;
temp->next = top;
top = temp;
printf("This is top %s\n", top->var);
}
j = 0;
} else {
*(t+j) = *p;
printf("%c\n", *p);
j++;
}
if(*p == '\0') {
break;
}
//printf("%c",*p);
p++;
}
struct rev *show;
show = top;
while(show != NULL) {
printf("%s\n", show->var);
show = show->next;
}
getch();
}
It is storing correctly but on traverse it is giving only the final element.
i am not be able to figure it out what is the problem.
Here is my output window:-
Read complete line. Tokenize string on whitespace, pushing each word to the stack. Pop the stack while printing.
Useful functions:
fgets
strtok
Complete solution can be done in less than 20 lines (including structure definitions, header files, etc.)
You also have a problem with undefined behavior in your code. You have a pointer p which points to a constant array of characters (all string literals are constant arrays of characters). Then you try to modify that constant array.
You might want something like this instead:
char arr[] = "Some string here";
char *p = arr;
And you have another case of undefined behavior as well: You have the pointer t which is not initialized. You then continue to dereference it. I would say that you are lucky to not get a crash.
You also don't update t in the loop, which you probably should.
First of all your char *t is just a pointer, make it point to malloced memory and then go ahead... I dont understand how the code is even running ... You are doing *(t + j) when t is actually pointing to junk.
On first look You are overwriting t... after parsing a string. i.e you set j = 0 and overwrite previously stored string and your struct rev hold a pointer to this t hence
you are getting you? you? you? as output. instead of having char *var in struct rev point to t .. your char *var point to a malloced memory and do strcpy or strtok
I just did a rough modification of your code and it worked for me on linux + gcc ... Here's the code:
#include<stdio.h>
#include <stdlib.h>
struct rev
{
char *var;
struct rev *next;
};
struct rev *top=NULL;
struct rev *temp,*test;
main()
{
int start, j = 0;
char *p="How are you?";
char *s;
char *t;
t = malloc(1000);
if (t == NULL) {
//OUT OF MEMORY
exit(1);
}
s = p;
while(1) {
if(*p == ' '|| *p == '\0') {
printf("Inside if \n");
*(t + j) = '\0';
printf("This is t %s\n",t);
if(top == NULL) {
temp = (struct rev *)malloc(sizeof(struct rev));
temp->next = NULL;
temp->var = malloc(100);
if (temp->var == NULL) {
//OUT OF MEMORY
exit(1);
}
strcpy(temp->var, t);
top = temp;
} else {
temp = (struct rev *)malloc(sizeof(struct rev));
printf("This is going in stack %s\n", t);
temp->var = malloc(100);
if (temp->var == NULL) {
//OUT OF MEMORY
exit(1);
}
strcpy(temp->var, t);
temp->next = top;
top = temp;
printf("This is top %s\n", top->var);
}
j = 0;
} else {
*(t+j) = *p;
printf("%c\n", *p);
j++;
}
if(*p == '\0') {
break;
}
//printf("%c",*p);
p++;
}
struct rev *show;
show = top;
while(show != NULL) {
printf("%s\n", show->var);
show = show->next;
}
//getch();
}
Here's the output:
H
o
w
Inside if
This is t How
a
r
e
Inside if
This is t are
This is going in stack are
This is top are
y
o
u
?
Inside if
This is t you?
This is going in stack you?
This is top you?
you?
are
How
PS: I dont undertand in which part of the code you are implementing push|pop ... You are using list and telling you want a stack. Stack and List are 2 different data-structures.
You can start by initializing variable t to point to a valid memory address.
It seems that the logic of "show" is written incorrectly-
show = top;
while(show != NULL) {
printf("%s\n", show->var);
show = show->next;
}
pointing show to top and printing "show->next" is incorrect way of popping out from stack.
Here is an example of pop function-
int pop(STACK **head) {
if (empty(*head)) {
fputs("Error: stack underflow\n", stderr);
abort();
} else {
STACK *top = *head;
int value = top->data;
*head = top->next;
free(top);
return value;}}
Related
I am building a program for a project. One of the requirements for the project is a function that selects a random node from my linked list of 3000 words.
I tried to do this by creating a function that generates a random number from 0 to 2999. After this, I created another function that follows a for loop starting from the head and moving to the next node (random number) times.
My random number generator is working fine, but my chooseRand() function is not.
Please help, the random number generator and the chooseRand() function are the last two functions above main. Also, my code is a bit messy, sorry.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>
int nodeNum;
int chances;
char* secret;
/*Node of linked list*/
typedef struct node {
char *data;
struct node *next;
} node;
node *start = NULL;
node *current;
/*Void function to print list*/
void printList(struct node *node)
{
while (node != NULL) {
printf("%s ", node->data);
node = node->next;
}
}
/*Appending nodes to linked list*/
void add(char *line) {
node *temp = malloc(sizeof(node));
temp->data = strdup(line);
temp->next = NULL;
current = start;
if(start == NULL) {
start = temp;
} else {
while(current->next != NULL) {
current = current->next;
}
current->next = temp;
}
}
void readfile(char *filename) {
FILE *file = fopen(filename, "r");
if(file == NULL) {
exit(1);
}
char buffer[512];
while(fgets(buffer, sizeof(buffer), file) != NULL) {
add(buffer);
}
fclose(file);
}
node *listSearch(node* start, char *nodeSearched){
node *p;
for (p = start; p != NULL; p = p->next)
if (strcmp(p->data, nodeSearched) == 0)
printf("%s", p->data);
return NULL;
}
node *letterSearch(node* start, int i){
node *p;
for (p = start; p != NULL; p = p->next)
if (strlen(p->data) == i)
{
printf("\n %s", p->data);
free(p);
p = NULL;
}
return NULL;
}
void chooseRand(struct node* start)
{
node* p;
int n;
p = start;
for(n = 0; n != nodeNum; n++)
{
p = p->next;
}
printf("%s", p->data);
}
void randNum(int lower, int upper)
{
srand(time(0));
nodeNum = (rand() % (upper - lower + 1)) + lower;
}
int main(){
randNum(0, 2999);
chooseRand(start);
return 0;
}
As others has said, the problem is that you don't have initialized the linked list yet, because of what your are getting a segmentation fault. So, in addition to initializing the list first, you must also introduce checks in the implementation of the chooseRand function, to check that if you reach the end of the list, without reaching the desired index, you stop executing the foor loop, otherwise you will be potentially exposed to segmentation faults.
Improve chooseRand implementation, to prevent segmentation fault either, when the linked list is empty, or when the randomly generated nodeNum is grater than the the index of the list's last item:
void chooseRand(struct node* start)
{
node* p;
int n;
p = start;
if(p == NULL){
printf("The list is empty!");
return;
}
// Also, we must stop the iteration, if we are going to pass the end of the list, you don't want a segmentation fault because trying to access a NULL pointer:
for(n = 0; n != nodeNum && p->next != NULL; n++)
{
p = p->next;
}
// If p == NULL, the list was not big enough to grab an item in the `nodeNum` index:
printf("%s", (n != nodeNum) ? "Not found!" : p->data);
}
Initialize the linked list, with the content of some file on disk:
int main(){
randNum(0, 2999);
// Fill the linked list with the content of a file in disk, calling your method:
char fileName[] = "PutYourFileNameHere.txt";
readfile(fileName);
chooseRand(start);
return 0;
}
There is another fix that you must do, and it is free the memory being hold by the pointer field data of your structure, in the implementation of your method letterSearch. Inside the if statement, you're de-allocating the memory hold by the p pointer, but you aren't de-allocating the memory assigned to the pointer p->data, this will cause a memory leak. When you in the function add, initialized p->data with the result of the call to the function strdup(line), what this function does is allocate enough memory in the heap, copies to it the buffer pointed by the line argument, and give to you back a pointer to the new allocated memory, that you're storing in the p.data field; a pointer that you should free when you're done with it, otherwise your program will have potential memory leaks. So I will modify your function letterSearch as folollows:
node *letterSearch(node* start, int i){
node *p;
for (p = start; p != NULL; p = p->next)
if (strlen(p->data) == i)
{
printf("\n %s", p->data);
// Free p->data before free p:
free(p->data);
free(p);
p = NULL;
}
return NULL;
}
References:
strdup
I am new to C programming. I am trying to do the pset5 in CS50 while trying to understand the concepts of memory, linked list and hashtable. I wrote the code and it compiled but there seems to be something wrong because every time I tried to execute the code it returns some garbage value. Could anyone please help me with that? Many thanks.
#include<stdio.h>
#include<stdlib.h>
#include<ctype.h>
#include<string.h>
#include "dictionary.h"
#define DICTIONARY "dictionaries/small"
typedef struct node
{
char WORD[LENGTH + 1];
struct node *next;
}
node;
int hash(char *word);
int main(void)
{
node **HASHTABLE = malloc(sizeof(node) * 26);
//open the dictionary
FILE *dic = fopen(DICTIONARY, "r");
if (dic == NULL)
{
fprintf(stderr, "Could not open the library\n");
return 1;
}
int index = 0;
char word[LENGTH + 1];
for (int c = fgetc(dic); c != EOF; c = fgetc(dic))
{
word[index] = c;
index++;
if (c == '\n')
{
int table = hash(word);
printf("%d\n", table);
//create a newnode
node *newnode = malloc(sizeof(node));
strcpy(newnode->WORD, word);
newnode->next = NULL;
printf("Node: %s\n", newnode->WORD);
index = 0;
//add new node to hash table
if (HASHTABLE[table] == NULL)
{
HASHTABLE[table] = newnode;
}
else
{
HASHTABLE[table]->next = newnode;
}
}
}
for(int i = 0; i < 26; i++)
{
node *p = HASHTABLE[i];
while (p != NULL)
{
printf("%s", p->WORD);
p = p->next;
}
}
//free memory
for(int i = 0; i < 26; i++)
{
node *p = HASHTABLE[i];
while (p != NULL)
{
node *temp = p->next;
free(p);
p = temp;
}
}
free(HASHTABLE);
}
int hash(char *word)
{
int i = 0;
if (islower(word[0]))
return i = word[0] - 'a';
if (isupper(word[0]))
return i = word[0] - 'A';
return 0;
}
Your code has serious problems that result in undefined behavior.
Two of them are the result of this line:
node **HASHTABLE = malloc(sizeof(node) * 26);
That allocates 26 node structures, but the HASHTABLE variable expects the address of a pointer to an array of node * pointers (that's the ** in the node **HASHTABLE declaration).
So, you should replace it with something like:
node **HASHTABLE = malloc( 26 * sizeof( *HASHTABLE ) );
Note that I used the dereferenced value of the variable being assigned to - HASHTABLE. This means in this case a node (one less * than in the declaration). So if the type of HASHTABLE changes, you don't need to make any other changes to the malloc() statement.
That problem, while technically undefined behavior, likely wouldn't cause any problems.
However, there's still a problem with
node **HASHTABLE = malloc( 26 * sizeof( *HASHTABLE ) );
that will cause problems - and serious ones.
That array of 26 pointers isn't initialized - you don't know what's in them. They can point anywhere. So this won't work well, if at all:
if (HASHTABLE[table] == NULL)
Meaning this points off to somewhere unknown:
HASHTABLE[table]->next = newnode;
And that will cause all kinds of problems.
The simplest fix? Initialize the values all to zero by using calloc() instead of malloc():
node **HASHTABLE = calloc( 26, sizeof( *HASHTABLE ) );
Until that's fixed, any results from your entire program are questionable, at best.
The reason for the garbage is that you didn't null-terminate the string:
strcpy(newnode->WORD, word);
strcpy expects the src to point to a null-terminated string. Simply adding 0 at the end. Simply terminate it with
word[index] = 0;
before the strcpy.
Other than that, the ones in Andrew Henle's answer should be addressed too, but I am not going to repeat them here.
BTW, next you will notice that
HASHTABLE[table]->next = newnode;
wouldn't work properly - that code always inserts the node as the 2nd one. But you want to always insert the new node unconditionally as the head, with
newnode->next = HASHTABLE[table];
HASHTABLE[table] = newnode;
There need not be any special condition for inserting the first node to a bucket.
I'm trying to setup a graph in C. I tried the graph with user input and it works perfectly. However, i am trying to implement a read from file. The last else statement is where the error is coming from because when i commented it out it compiles without any problems. I have included a comment over the block i think that has the problem. Please let me know if there is anything else needed for this question.
#include <stdio.h>
#include <stdlib.h>
struct node{
int data;
struct node* next;
};
//int counter and mainVertex would be used to determine if graph is connected.
// void graphConnection(){
//
//
//
//
//
//
// }
char* deblank(char* input)
{
int i,j;
char *output=input;
for (i = 0, j = 0; i<strlen(input); i++,j++)
{
if (input[i]!=' ')
output[j]=input[i];
else
j--;
}
output[j]=0;
return output;
}
struct node *G[1000];
int counter = 0;
char *mainVertex;
void readingEachLine(){
FILE * fp;
char * line = NULL;
size_t len = 0;
ssize_t read;
//Read file and exit if fail
fp = fopen("test.txt", "r");
if (fp == NULL)
exit(EXIT_FAILURE);
while ((read = getline(&line, &len, fp)) != -1) {
line = deblank(line);
int i = 0;
struct node* cursor = malloc(sizeof(struct node));
struct node* secondcursor = malloc(sizeof(struct node));
struct node* tempitem;
while(line[i] != '\n'){
//If its the first of the line look into the array and set struct cursor to the corresponding
//array position
if (i == 0){
mainVertex[counter] = line[0];
int convertor = line[i] - '0';
cursor = G[convertor];
counter++;
}
//if its not the first, then set a struct with that number as data
else{
tempitem = malloc(sizeof(struct node));
int convertor = line[i] - '0';
tempitem->data = convertor;
tempitem->next = NULL;
}
//if there is no element connected to the struct in array, connect the tempitem
if (cursor->next == NULL){
cursor->next = tempitem;
}
//If there are already connected elements, loop until the end of the linked list
//and append the tempitem
//ERROR: I GET SEGMENTATION FAULT FROM HERE. TRIED AFTER COMMENTING IT OUT
else{
secondcursor = cursor;
while(secondcursor->next != NULL){
secondcursor = secondcursor->next;
}
secondcursor->next = tempitem;
}
i++;
}
printf("\n");
}
}
int main(void){
for (int i = 1; i < 1000; i++)
{
G[i]= malloc(sizeof(struct node));
G[i]->data = i;
G[i]->next = NULL;
}
readingEachLine();
}
EDIT: This is how the text file looks like:
1 3 4
2 4
3 1 4
4 2 1 3
Your code has several misconceoptions:
Apparently, you can have a maximum of 1,000 nodes. You have an array G of 1,000 head pointers to linked lists. Don't allocate memory for all 1,000 nodes at the beginning. At the beginning, all lists are empty and an empty linked list is one that has no node and whose head is NULL.
In your example, cursor is used to iterate oer already existing pointers, so don't allocate memory for it. If you have code like this:
struct node *p = malloc(...);
// next use of p:
p = other_node;
you shouldn't allocate. You would overwrite p and lose the handle to the allocated memory. Not all pointers have to be initialised with malloc; allocate only if you create a node.
Your idea to strip all spaces from a line and then parse single digits will fail if you ever have more then 9 nodes. (But you cater for 1,000 node.) Don't try to parse the numbers yourself. There are library functions for that, for example strtol.
It is not clear what mainVertex is supposed to be. You use it only once, when you assign to it. You treat it like an array, but it is a global pointer, initialised to NULL. When you dereference it, you get undefined behaviour, which is where your segmentation fault probably comes from.
Here's a program that does what you want to do. (It always inserts nodes at the head for simplicity and it should have more allocation checks.)
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
enum {
maxNodes = 1000
};
struct node{
int data;
struct node* next;
};
struct node *G[maxNodes];
size_t nnode = 0;
int read_graph(const char *fn)
{
FILE * fp;
char * line = NULL;
size_t len = 0;
fp = fopen(fn, "r");
if (fp == NULL) return -1;
while (getline(&line, &len, fp) != -1) {
char *p;
char *end;
int id;
int n;
id = strtol(line, &end, 10);
if (end == line) continue;
if (id < 1 || id > maxNodes) break;
if (id > nnode) nnode = id;
id--;
p = end;
n = strtol(p, &end, 10);
while (p != end) {
struct node *nnew = malloc(sizeof(*nnew));
nnew->data = n - 1;
nnew->next = G[id];
G[id] = nnew;
p = end;
n = strtol(p, &end, 10);
}
}
fclose(fp);
free(line);
return 0;
}
int main(void)
{
if (read_graph("test.txt") < 0) {
fprintf(stderr, "Couldn't gread raph.\n");
exit(1);
}
for (int i = 0; i < nnode; i++) {
struct node *p = G[i];
if (p) {
printf("%d:", i + 1);
for (; p; p = p->next) {
printf(" %d", p->data + 1);
}
puts("");
}
}
for (int i = 0; i < nnode; i++) {
struct node *p = G[i];
while (p) {
struct node *old = p;
p = p->next;
free(old);
}
}
return 0;
}
I'm getting a segmentation fault when I do free() in the delete function of the following linked list implementation. Please take a look and tell me where I am going wrong. When I run this program with valgrind, there is no seg. fault, it runs fine. So I am not able to figure out the problem.
typedef struct node {
char name[100];
int id;
struct node* next;
} Node;
void insert(Node** p, char* _name, int _id)
{
Node *temp, *prev;
temp = malloc(sizeof(struct node));
temp->next = NULL;
strcpy(temp->name,_name);
temp->id = _id;
if(*p == NULL) {
*p = temp;
}
else {
for(prev = *p; prev->next!=NULL; prev=prev->next);
prev->next=temp;
}
}
/* Delete entry
#params p first element
_id ID to delete
*/
void delete_by_id(Node** p, int _id) {
Node *temp, *prev;
prev = NULL;
for(temp = *p; temp!= NULL; prev = temp, temp=temp->next) {
if(temp->id == _id) {
printf("Deleting entry with id: %d\n", temp->id);
if(prev == NULL)
*p = temp->next;
else
prev->next= temp->next;
free(temp);
return;
}
}
}
Here is part of the code from the main program:
Node* p;
int main() {
...
...
buf[rval]=0;
char* tokens = strtok(buf, "+");
char* strArray[5]; /* up-to 5 words can be stored */
int n = 0;
while (tokens)
{
strArray[n] = malloc(strlen(tokens) + 1);
strcpy(strArray[n++], tokens);
tokens = strtok(NULL, "+");
}
int type = 0;
if(strcmp(strArray[0], "1") == 0)
type = 1;
else
type = 2;
char* name = "";
if(type == 1) {
name = strArray[1];
insert(&p, name, clients[i]);
display(&p);
} else {
name = strArray[1];
rval = search(&p, name);
if(rval) {
delete_by_id(&p, rval);
display(&p);
}
}
for (i = 0; i < 5; i++)
{
if (strArray[i]) // check for null data
free(strArray[i]);
}
...
...
}
int search(Node** p, char* _name) {
Node *temp;
for (temp = *p; temp!= NULL; temp = temp->next) {
if (strcmp((char *)temp->name, _name)==0) {
printf("Name matched: %s\n", temp->name);
return temp->id;
}
}
return 0;
}
Valgrind is complaining about the malloc and free used for strArray but not for the linked list.
Print out the addresses returned by malloc(), and also print out the value of temp immediately before the call to free(). Make sure that what's being passed to free() matches what you expect. If somehow you are passing a pointer to free() that didn't come from malloc(), you can encounter problems like you are seeing.
There's also a possibility that the function delete_by_id() is using an invalid pointer. The p parameter is dereferenced before it's checked for NULL. I recommend walking through the function in your debugger and making sure that all of the pointers look as you expect them to look.
Let your program dump core and analyze the core in GDB:
gdb -c yourprog.core yourprog
then do a full backtrace:
(gdb) bt full
This will show you where exactly the reason for your segfault is and what values were passed to the function.
(edit) Oh, and compile your program with the GCC -g switch to have debugging information.
Run your program through valgrind. Segfaults on free are usually due to writes outside of the allocated memory (which overwrites/corrupts the wrappers that the system places before/after allocated memory). Valgrind is usually the easiest way to find out when the writes in question happens.
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.