Segmentation fault on assigning int - c

I am following the video series "Coding a Rogue/Nethack clone in c" and getting a segfault despite the fact that the creator isn't.
This is using ncurses and the menu library.
gdb says it's in the function handleInput, when I try to set the x and y.
Pos* handleInput(int input, Player* user) {
Pos * newPosition;
newPosition = malloc(sizeof(Pos));
switch (input)
{
/* move up */
case 'w':
case 'W':
newPosition->y = user->pos->y - 1;
newPosition->x = user->pos->x;
break;
/* move down */
case 's':
case 'S':
newPosition->y = user->pos->y + 1;
newPosition->x = user->pos->x;
break;
/* move left */
case 'a':
case 'A':
newPosition->y = user->pos->y;
newPosition->x = user->pos->x - 1;
break;
/* move right */
case 'd':
case 'D':
newPosition->y = user->pos->y; // Segfault here
newPosition->x = user->pos->x + 1;
default:
break;
Some typedefs:
typedef struct Level {
int level;
char** tiles;
int numRooms;
struct Player* user;
struct Room** room;
struct Monster** Mons;
int numMons;
} Level;
typedef struct Pos {
int x;
int y;
} Pos;
typedef struct Player {
Pos* pos;
int atk;
int maxHP;
int xp;
int gold;
int health;
} Player;
typedef struct Monster {
char string[2];
char symbol;
int alive;
int health;
int attack;
int speed;
int defense;
int pathfinding;
Pos* pos;
} Monster;
And my game function:
int gameLoop()
{
int ch;
Pos* newPosition;
Level * level;
level = createLevel(1);
Player* user = level->user;
printGameHud(level);
/* main game loop */
while ((ch = getch()) != 'q')
{
printGameHud(level);
newPosition = handleInput(ch, user);
checkPosition(newPosition, level);
moveMonster(level);
move(level->user->pos->y, level->user->pos->x);
if (level->user->health <= 0)
{
return -1;
}
}
return 1;
}
Finally, my menu function, which seems to be where this started:
void menuLoop () {
int choice;
while (true) {
char* choices[] = {"Start", "Exit"};
choice = mainMenu(2, choices);
switch (choice) {
case START_GAME:
gameLoop();
clear();
break;
case QUIT_GAME:
return;
}
}
}
int closeMenu(int numItems, MENU* menu, ITEM** items){
unpost_menu(menu);
free_menu(menu);
for (int i = 0; i < numItems; i++) {
free_item(items[i]);
}
return 1;
}
int mainMenu(int numItems, char* items[]) {
int c, i, value;
MENU* menu;
ITEM* current;
ITEM** menuItems = malloc(sizeof(**menuItems) * numItems);
for (i = 0; i < numItems; i++) {
menuItems[i] = new_item(items[i], "");
}
menuItems[i] = (ITEM*)NULL;
menu = new_menu((ITEM**)menuItems);
post_menu(menu);
refresh();
while (true) {
c = getch();
switch(c){
case KEY_DOWN:
menu_driver(menu, REQ_DOWN_ITEM);
break;
case KEY_UP:
menu_driver(menu, REQ_UP_ITEM);
break;
case 10:
current = current_item(menu);
value = item_index(current);
closeMenu(numItems, menu, menuItems);
return value;
}
}
}

Related

In this trie data structure implementation the display function is not working.Why?

When i display I am getting different answer but search is working. It could be a semantic error.Please help to correct it. It could have an error somewhere. I don't know where is it.Please help me to find it.The insert does not work in the program.It could be an error somewhere.I need this trie data structure to work.
#include<stdio.h>
#include<stdlib.h>
#define maxlength 10
typedef struct node
{
int isend;
struct node *branch[27];
}trinode;
int len,count;
trinode *createnode()
{
trinode *new=(trinode *)malloc(sizeof(trinode));
int ch;
for(ch=0;ch<27;ch++)
{
new->branch[ch]=NULL;
}
new->isend=0;
return new;
}
trinode *insert_trie(trinode *root,char *newenty)
{int ind;
trinode *proot;
if(root==NULL)
root=createnode();
proot=root;
for(int i=0;i<maxlength;i++)
{
ind=newenty[i]-'a';
if(newenty[i]=='\0')
break;
else
{
if(root->branch[ind]==NULL)
root->branch[ind]=createnode();
root=root->branch[ind];
}
}
if(root->isend!=0)
printf("trying to insert duplicate");
else
root->isend=1;
return proot;
}
void print_trie(trinode *cur)
{
int count;
char word[40];
for(int i=0;i<26;i++)
{
if(cur->branch[i]!=NULL)
{
word[count++]=(i+'a');
if((cur->branch[i]->isend)==1)
{
printf("\n");
for(int j=0;j<count;j++)
{
printf("%c",word[j]);
}
}
print_trie(cur->branch[i]);
}
}
count--;
}
int search_trie(trinode *root,char *target)
{
int ind;
for(int i=0;i<maxlength &&root;i++)
{
ind=target[i]-'a';
if(target[i]=='\0')
break;
else
root=root->branch[ind];
}
if(root && root->isend==1)
return 1;
else
return 0;
}
int main()
{
int ch;
trinode *root=NULL;
char *newenty;
char *target;
int check;
newenty = (char *)malloc(maxlength);
target= (char *)malloc(maxlength);
while(1)
{
printf("\n enter option 1.insert_trie 2.display 3.search 4.exit");
scanf("%d",&ch);
switch(ch)
{
case 1:
printf("enter word");
scanf("%s",newenty);
root=insert_trie(root,newenty);
break;
case 2:
count =0;
print_trie(root);
break;
case 3:
printf("enter elem you want to search");
scanf("%s",target);
check=search_trie(root,target);
if(check==0)
printf("word not found");
else
printf("found");
break;
case 4:
exit(0);
break;
}
}
}

trying to free dynamic allocated memory

So i know this might be asking too much but in my program i used valgrind for some reason it always says that i have 9 allocs mad and 1 free made, but in my code i freed all of the arrays i used, so i dont know are the allocs not being freed.
So if anyone could help me i would appreciate it a lot because im not understanding whats wrong in my code.
Program:
#include<stdlib.h>
#include<stdio.h>
#include <string.h>
#define MAX_CHARS 1024 /* max characters of a word */
#define MAX_SIZE 5
static int line = 1; /* counts the number of lines of the stdin */
int ident = 0; /*counts the id of jogos*/
static int size_until = 0; /*counts the size of sistema_eq*/
static int size_until2 = 0;/*counts the size of conj_jogos*/
char **sistema_eq;
typedef struct
{
int id;
char equipas[2][1024];
int pont[2];
char nome[MAX_CHARS];
} jogo;
typedef struct
{
int id;
char nome[MAX_CHARS];
int vit;
} vitorias;
/*-----------------------------------------*/
jogo *conj_jogos;
vitorias *conj_vit;
void a(char nome_jg[],char team1[],char team2[],int score1,int score2);
void A(char nome[]);
int main()
{
char c;
char nome_jg[MAX_CHARS], team1[MAX_CHARS], team2[MAX_CHARS];
int score1;
int score2;
int i;
conj_jogos = (jogo*)calloc(MAX_SIZE,sizeof(jogo));
conj_vit = (vitorias*)calloc(MAX_SIZE,sizeof(vitorias));
sistema_eq = (char**)calloc(MAX_SIZE,sizeof(*sistema_eq));
for(i=0;i<MAX_SIZE;i++)
{
sistema_eq[i] = (char*)calloc(1024,sizeof(char));
}
while ((c = getchar())!= 'x') {
switch (c)
{
case 'A':
{
scanf("%1023[^:\n]",nome_jg);
remove_esp(nome_jg);
A(nome_jg);
break;
}
case 'a':
{
scanf("%1023[^:\n]:%1023[^:\n]:%1023[^:\n]:%d:%d",nome_jg,team1,team2,&score1,&score2);
remove_esp(nome_jg);
a(nome_jg,team1,team2,score1,score2);
line++;
break;
}
}
}
free(conj_vit);
free(conj_jogos);
for(i=0;i<size_until;i++) free(sistema_eq[i]);
free(sistema_eq);
return 0;
}
void A(char nome[])
{
if (nome_in_sis(nome) == 1)
{
printf("%d Equipa existente.\n",line);
line++;
}
else
{
if (size_until < MAX_SIZE)
{
strcpy(sistema_eq[size_until],nome);
strcpy(conj_vit[size_until].nome,nome);
conj_vit[size_until].id = size_until;
size_until++;
line++;
}
else
{
conj_vit = realloc(conj_vit,sizeof(vitorias)*(size_until+1));
sistema_eq = realloc(sistema_eq,sizeof(char*)*(size_until+1));
sistema_eq[size_until] = calloc(1024,sizeof(char*));
strcpy(sistema_eq[size_until],nome);
strcpy(conj_vit[size_until].nome,nome);
conj_vit[size_until].id = size_until;
size_until++;
line++;
}
}
}
void a(char nome_jg[],char team1[],char team2[],int score1,int score2)
{
int vit;
if (jogo_in(nome_jg) == 1)
{
printf("%d Jogo existente.\n",line);
line++;
}
else if ((nome_in_sis(team1) == 0) || (nome_in_sis(team2) == 0))
{
printf("%d Equipa inexistente.\n",line);
line++;
}
else
{
if (size_until2 < MAX_SIZE)
{
conj_jogos[size_until2] = cria_jogo(nome_jg,team1,team2,score1,score2);
if (score1 > score2)
{
vit = procura_vit(team1);
conj_vit[vit].vit++;
}
else
{
vit = procura_vit(team2);
conj_vit[vit].vit++;
}
size_until2++;
}
else
{
size_until2++;
conj_jogos = realloc(conj_jogos,sizeof(jogo)*(size_until2+1));
conj_jogos[size_until2] = cria_jogo(nome_jg,team1,team2,score1,score2);
if (score1 > score2)
{
vit = procura_vit(team1);
conj_vit[vit].vit++;
}
else
{
vit = procura_vit(team2);
conj_vit[vit].vit++;
}
size_until2++;
}
}
}

Expected '(' for function-style or type construction

So I'm trying to call a function in my main function within my switch function and it's telling me "expected '(' for function-style or type construction." What am I doing wrong here causing this error? I can't seem to figure it out. Thanks.
#include <stdio.h>
#include <stdlib.h>
#define ARRAY_SIZE 6
#include <string.h>
typedef struct
{
char name[100];
unsigned int accountId;
float accountBalance;
int yearJoined;
} BankingInfo;
void createTestData(BankingInfo inventory[]){
strcpy(inventory[0].name, "Alex");
inventory[0].accountId = 1001;
inventory[0].accountBalance = 2390;
inventory[0].yearJoined = 2001;
strcpy(inventory[1].name, "Bill");
inventory[1].accountId = 1003;
inventory[1].accountBalance = 10000;
inventory[1].yearJoined = 2012;
strcpy(inventory[2].name, "Craig");
inventory[2].accountId = 1004;
inventory[2].accountBalance = 500;
inventory[2].yearJoined = 1994;
strcpy(inventory[3].name, "David");
inventory[3].accountId = 1008;
inventory[3].accountBalance = 5836;
inventory[3].yearJoined = 2013;
strcpy(inventory[4].name, "Eric");
inventory[4].accountId = 1016;
inventory[4].accountBalance = 90;
inventory[4].yearJoined = 1999;
strcpy(inventory[5].name, "Felix");
inventory[5].accountId = 1032;
inventory[5].accountBalance = 5703;
inventory[5].yearJoined = 2003;
}
void outputTable(BankingInfo inventory[], int size){
int i;
printf("Names\tID\t\tAccount Balance\t\tYear Joined\n");
for (i = 0; i < ARRAY_SIZE; i++) {
printf("%s\t%u\t %.2lf\t\t\t%i\n",
inventory[i].name,inventory[i].accountId,
inventory[i].accountBalance, inventory[i].yearJoined);
}
}
void searchById(BankingInfo inventory[], int size, int id){
unsigned int enteredId;
int i;
printf("Enter ID number: ");
scanf("%u", &enteredId);
for (i = 0; i < ARRAY_SIZE; i++) {
if (inventory[i].accountId == enteredId) {
printf(inventory[i].name,inventory[i].accountId,
inventory[i].accountBalance, inventory[i].yearJoined);
}
}
}
void searchByYear(BankingInfo inventory[], int size, int year){
unsigned int enteredYear;
int i;
printf("Enter year joined: ");
scanf("%u", &enteredYear);
for (i = 0; i < ARRAY_SIZE; i++) {
if (inventory[i].yearJoined == enteredYear) {
printf(inventory[i].name,inventory[i].accountId,
inventory[i].accountBalance, inventory[i].yearJoined);
}
}
}
int main(void){
int choice;
BankingInfo inventory[ARRAY_SIZE];
createTestData(inventory);
outputTable(inventory, ARRAY_SIZE);
do{
printf("Enter 1 to search by ID\n");
printf("Enter 2 to search by year joined\n");
printf("Enter 3 to finish\n");
switch (choice) {
case 1:
searchById(inventory, ARRAY_SIZE, int id);
break;
case 2:
searchByYear(inventory, ARRAY_SIZE, int year);
break;
case 3:
break;
default:
printf("Not a valid choice\n");
break;
}
}while (choice != 3);
return 1;
}
You have a type specifier in a function call parameter, twice like this
searchById(inventory, ARRAY_SIZE, int id);
/* ^ this ???? */
just remove it
searchById(inventory, ARRAY_SIZE, id);
and then declare and initialize id and year.
I've fixed your program, I hope you can understand what I did
#include <stdio.h>
#include <stdlib.h>
#define ARRAY_SIZE 6
#include <string.h>
typedef struct
{
char name[100];
unsigned int accountId;
float accountBalance;
int yearJoined;
} BankingInfo;
void createTestData(BankingInfo inventory[])
{
strcpy(inventory[0].name, "Alex");
inventory[0].accountId = 1001;
inventory[0].accountBalance = 2390;
inventory[0].yearJoined = 2001;
strcpy(inventory[1].name, "Bill");
inventory[1].accountId = 1003;
inventory[1].accountBalance = 10000;
inventory[1].yearJoined = 2012;
strcpy(inventory[2].name, "Craig");
inventory[2].accountId = 1004;
inventory[2].accountBalance = 500;
inventory[2].yearJoined = 1994;
strcpy(inventory[3].name, "David");
inventory[3].accountId = 1008;
inventory[3].accountBalance = 5836;
inventory[3].yearJoined = 2013;
strcpy(inventory[4].name, "Eric");
inventory[4].accountId = 1016;
inventory[4].accountBalance = 90;
inventory[4].yearJoined = 1999;
strcpy(inventory[5].name, "Felix");
inventory[5].accountId = 1032;
inventory[5].accountBalance = 5703;
inventory[5].yearJoined = 2003;
}
void outputTable(BankingInfo inventory[], int size)
{
int i;
printf("Names\tID\t\tAccount Balance\t\tYear Joined\n");
for (i = 0; i < ARRAY_SIZE; i++)
{
printf("%s\t%u\t\t%5.2lf\t\t%d\n",
inventory[i].name,
inventory[i].accountId,
inventory[i].accountBalance,
inventory[i].yearJoined
);
}
}
void searchById(BankingInfo inventory[], int size, int id)
{
int i;
for (i = 0; i < ARRAY_SIZE; i++)
{
if (inventory[i].accountId == id)
{
printf("%s\t%u\t\t%5.2lf\t\t%d\n",
inventory[i].name,
inventory[i].accountId,
inventory[i].accountBalance,
inventory[i].yearJoined
);
}
}
}
void searchByYear(BankingInfo inventory[], int size, int year){
unsigned int enteredYear;
int i;
printf("Enter year joined: ");
scanf("%u", &enteredYear);
for (i = 0; i < ARRAY_SIZE; i++)
{
if (inventory[i].yearJoined == enteredYear)
{
printf("%s\t%u\t\t%5.2lf\t\t%d\n",
inventory[i].name,
inventory[i].accountId,
inventory[i].accountBalance,
inventory[i].yearJoined
);
}
}
}
int main(void)
{
char choice;
BankingInfo inventory[ARRAY_SIZE];
createTestData(inventory);
outputTable(inventory, ARRAY_SIZE);
do {
int id;
int year;
printf("\n");
printf("\t1 Search by ID\n");
printf("\t2 Search by year joined\n");
printf("\t3 Finish\n\n");
printf("Please input your choice > ");
scanf(" %c", &choice);
switch (choice)
{
case '1':
printf("Enter item id > ");
if (scanf("%d", &id) == 1)
searchById(inventory, ARRAY_SIZE, id);
else
printf("invalid input\n");
break;
case '2':
printf("Enter item year > ");
if (scanf("%d", &year) == 1)
searchByYear(inventory, ARRAY_SIZE, year);
else
printf("invalid input\n");
break;
case '3':
break;
default:
printf("Not a valid choice\n");
break;
}
} while (choice != '3');
return 0;
}

Evaluate postfix notation

I was doing my exercise but i stucked at the last step.
I have to evaluate postfix notation using stacks in C.
Code:
#include<stdio.h>
#include<stdlib.h>
#define MAX 100
typedef struct
{
int info;
}tipElement;
typedef struct
{
tipElement magacin [MAX];
int vrv;
}tipMagacin;
tipMagacin postfixStack;
void Inicijalizacija(tipMagacin *Mag)
{
(*Mag).vrv = -1; //warehouse is empty
}
int Prazen(tipMagacin Mag)
{
return(Mag.vrv == -1); //returns true if the warehouse is empty
}
int Poln(tipMagacin Mag)
{
return(Mag.vrv == MAX-1); //returns true if the warehouse is full
}
void Push(tipMagacin *Mag, tipElement Element)
{
if (Poln(*Mag)) printf("Warehouse is full\n"); //if it is full report an error
else
{
(*Mag).vrv++; //next position in the warehouse
(*Mag).magacin[(*Mag).vrv].info = Element.info; //put an element
}
}
void Pop(tipMagacin *Mag, tipElement *Element)
{
if (Prazen(*Mag)) printf("Warehouse is empty\n"); //if it is empty report an error
else
{
(*Element).info = (*Mag).magacin[(*Mag).vrv].info; //read the last element
(*Mag).vrv--; // delete it
}
}
int evaluate(int op1, int op2, char operate) {
switch (operate) {
case '*': return op2 * op1;
case '/': return op2 / op1;
case '+': return op2 + op1;
case '-': return op2 - op1;
default : return 0;
}
}
int evaluatePostfix (char *izraz, int n)
{
tipMagacin *Mag;
tipElement element;
tipElement go,z;
int i=0;
int op2;
char ch;
int value;
while (i < n) {
element.info = izraz[i];
if(isdigit(element.info))
{
Push(&postfixStack, element);
}
else
{
z=Pop(&postfixStack, &go);
op2=1;
value = evaluate(z,op2,ch);
Push(Mag,value);
}
i++;
}
return value;
}
my code works fine until here:
else
{
op1=Pop(&postfixStack, &go);
op2=Pop(&postfixStack, &go);
value = evaluate(op1,op2,element.info);
Push(&postfixStack, value);
}
i++;
}
return value;
}
the problem is: error: void value not ignored as it ought to be
my Push and Pop functions are void and i need to put the value that I remove from my stack to some int variable then i calculate them. put it doesnt put it for some reason i dont know.
Anyone help ?

error using structs, C

i am getting the error "a3.c:221:20: error: storage size of ‘gold’ isn’t known" for all 4 of my item structs. My code is as follows:
void parser(int argc, char **argv)
{
FILE * rooms;
char * theString;
char * theToken;
int numberElements;
int side;
int k;
int placeInt;
int posX;
int posY;
char a[ROOM_STRING_LENGTH];
numberElements = 0;
rooms = fopen(argv[1], "r");
if(rooms == NULL)
{
printf("error opening file\n");
}
while(fgets(a, ROOM_STRING_LENGTH, rooms) != NULL)
{
theString = malloc((sizeof(char)*(strlen(a)+1)));
strcpy(theString, a);
for(theToken = strtok(theString, " "); theToken; theToken = strtok(NULL, " "))
{
printf("the next token: %s\n", theToken);
if(theToken[0] == '1')
{
}
if(theToken[0] == 'd')
{
switch(theToken[1])
{
case 'e':
{
side = 1;
placeInt = theToken[2] - '0';
printf("the side: %d, the place: %d\n", side, placeInt);
break;
}
case 'w':
{
side = 2;
placeInt = theToken[2] - '0';
printf("the side: %d, the place: %d\n", side, placeInt);
break;
}
case 's':
{
side = 3;
placeInt = theToken[2] - '0';
printf("the side: %d, the place: %d\n", side, placeInt);
break;
}
case 'n':
{
side = 4;
placeInt = theToken[2] - '0';
printf("the side: %d, the place: %d\n", side, placeInt);
break;
}
default:
{
break;
}
}
}
else if(theToken[0] == 'g' || theToken[0] == 'm' || theToken[0] == 'p' || theToken[0] == 'h')
{
k = 0;
while(k <= (strlen(theToken)))
{
switch(theToken[k])
{
case 'g':
posY = theToken[1] - '0';
posX = theToken[3] - '0';
struct item gold;
gold.Xposition = posX;
gold.Yposition = posY;
printf("the y position: %d, the x position: %d\n", posY, posX);
break;
case 'm':
posY = theToken[1] - '0';
posX = theToken[3] - '0';
struct item monster;
monster.Xposition = posX;
monster.Yposition = posY;
printf("the y position: %d, the x position: %d\n", posY, posX);
break;
case 'p':
posY = theToken[1] - '0';
posX = theToken[3] - '0';
struct item potion;
potion.Xposition = posX;
potion.Yposition = posY;
printf("the y position: %d, the x position: %d\n", posY, posX);
break;
case 'h':
posY = theToken[1] - '0';
posX = theToken[3] - '0';
struct item hero;
hero.Xposition = posX;
hero.Yposition = posY;
printf("the y position: %d, the x position: %d\n", posY, posX);
break;
}
k++;
}
}
else if(theToken == NULL)
{
printf("end of file");
}
numberElements++;
}
if(theToken == NULL)
{
printf("You've reached the end of the line\n");
}
printf("%d\n", numberElements);
}
free(theString);
fclose(rooms);
}
struct item
{
int Xposition;
int Yposition;
};
Also, I was wondering how i would go about accessing the information i just stored into those structs in a different function.
As keltar and nonsensickle already mentioned, you have to define struct item before you can use an instance of it:
struct item { int x; int y; }; // this must come first
// ...
struct item item1 {4, 2};
You could, however, use a pointer before the definition, as long as you have already declared the struct:
struct item; // declaration, no definition
// ...
struct item *pitem1;
// ...
struct item { int x; int y; }; // defined later
To use a struct's members in another function, you could pass either a struct or a struct* to that function:
void use_struct (struct item i)
{
int a = i.x, b = i.y;
}
void use_struct_pointer (struct item *pi)
{
int a = pi->x, b = pi->y;
}
int main()
{
struct item i {4, 2};
use_struct(i);
use_struct_pointer(&i);
return 0;
}

Resources