I am working on a programming assignment in C, which is about creating basic automation for cinema halls.
For holding data of halls, I define a structure like this:
typedef struct {
char *hallName;
char *movieName;
seat** hallSeats;
int studentCount;
int fullFareCount;
int totalSum;
int width;
int height;
}Hall;
So I am given a text file with commands and whenever I came up with a specific command, I should create a separate hall. For that reason, I created another function for that.
Hall makeHall(char **temp) //TEMP HOLDING THE LINES FROM FILE
{
int width = strToInt(temp[3]);
int height = strToInt(temp[4]);
char currentRowLetter = 'A';
int currentRow;
int currentSeat;
seat **hall = malloc(sizeof(seat*) * width );
for (currentRow=0 ; currentRow < width ; currentRow++)
{
hall[currentRow] = malloc(sizeof(seat) * height );
for(currentSeat=0; currentSeat < height ; currentSeat++)
{
hall[currentRow][currentSeat].rowLetter = currentRowLetter;
hall[currentRow][currentSeat].seatNumber = currentSeat + 1;
hall[currentRow][currentSeat].seatTaken = ' ';
}
++currentRowLetter;
}
Hall newHall;
newHall.hallName = temp[1];
newHall.movieName = temp[2];
newHall.hallSeats = hall;
newHall.width = width;
newHall.height = height;
return newHall;
}
Since I will have multiple halls, I created a Hall array in order to access them later.
Hall *allHalls = malloc(sizeof(Hall) * 10); /*Hall placeholder*/
While I iterate over the lines, I check commands and create halls or sell tickets.
Hall *allHalls = malloc(sizeof(Hall) * 10); /*Hall placeholder*/
FILE *f;
f = fopen("input.txt", "rt");
char *line = malloc (sizeof(char) * 200); /*LINE HOLDER*/
int currentLineNumber = 0;
char *tmp;
int hallNumber = 0;
while (1) { /*PARSING FILE*/
if (fgets(line,200, f) == NULL) break; /*FILE END CHECKER*/
currentLineNumber++;
tmp = strtok(line," ");
char **temp = malloc(sizeof(char*) * 6);
int currentWordNumber = 0;
while(tmp != NULL) /*PARSING LINES*/
{
temp[currentWordNumber] = malloc(strlen(tmp) + 1);
strcpy(temp[currentWordNumber],tmp);
tmp = strtok (NULL, " ");
currentWordNumber++;
}
if(!strcmp("CREATEHALL",temp[0]))
{
allHalls[hallNumber] = makeHall(temp); /*<<<<<<<PROBLEM*/
hallNumber++;
printf("%d\n",hallNumber);
}
Now that's the part I am lost at. Whenever I tried to access the array, the program crashes.
I thought it was a memory problem, so increased memory allocated by malloc for allHalls to 40 (even though it should not be a problem, since file only gives 3 different halls) and program no longer crashes, but instead overwrites the previous hall in the array.
I tried multiple solutions but none of them came out any good, so closest I get is this.
I did use java a lot before, so I am still stuck to OOP and pretty new to C.
EDIT
Seat is defined as
typedef struct {
char rowLetter;
int seatNumber;
char seatTaken;
}seat;
also example createhall command is
CREATEHALL Hall_A Avatar 24 20
while the numbers at the end being width and height for hall
EDIT : CODE
I got the bug:
At the bottom of the while(1) loop in main you do a free(allHalls); so now there are no more halls and you get a segfault...
It was in the code you didn't show us:
while (1) {
...
if(!strcmp("CREATEHALL",temp[0]))
{
allHalls[hallNumber] = makeHall(temp); /*<<<<<<<PROBLEM*/
hallNumber++;
printf("%d\n",hallNumber);
}
....
free(temp);
free(allHalls); // <-- there's your bug
}
fclose(f);
free(line);
Related
So I have an assignment to create a program in c that reads a couple of sentences(a 140mb file), and based on the 2nd input, which is a number, I need to return the Nth most common word. My idea was to build a hash table with linear probing, every time I get a new element I hash it accordingly based its position and based on djb2, else if there is a collision I rehash. After that, I apply Quicksort based on the occurrence and then I finally access by index.
I am having issues finishing up a hash table with linear probing in c. I am pretty sure I have finished it but every time I run I am getting a heap buffer overflow on lldb. I tried to spot the issue but I still cannot figure it out.
Am I getting out of memory on stack? The file is relatively small to consume so much memory.
I used address sanitiser and I got a heap-buffer-overflow on inserting.
I don't think I am touching the memory outside the allocate region but I am not 100% sure.
Any idea what has gone wrong? This is the table.c implementation and below that you can see the form of the struct.
Here is a more detailed message from address sanitiser:
thread #1: tid = 0x148b44, 0x0000000100166b20 libclang_rt.asan_osx_dynamic.dylib`__asan::AsanDie(), queue = 'com.apple.main-thread', stop reason = Heap buffer overflow
{
"access_size": 1,
"access_type": 1,
"address": 105690555220216,
"description": "heap-buffer-overflow",
"instrumentation_class": "AddressSanitizer",
"pc": 4294981434,
"stop_type": "fatal_error"
}
table.c :
#include "table.h"
#include "entities.h"
static inline entry_t* entryInit(const char* const value){
unsigned int len = strlen(value);
entry_t* entry = malloc(sizeof(entry));
entry->value = malloc(sizeof(char*) * len);
strncpy(entry->value, value, strlen(value));
entry->exists = 1;
entry->occurence = 1;
return entry;
}
table_t* tableInit(const unsigned int size){
table_t* table = malloc(sizeof(table_t));
table->entries = malloc(size*sizeof(entry_t));
table->seed = getPrime();
table->size = size;
table->usedEntries = 0U;
return table;
}
//okay, there is definitely an issue here
table_t* tableResize(table_t* table, const unsigned int newSize){
//most likely wont happen but if there is an overflow then we have a problem
if(table->size > newSize) return NULL;
//create a temp array of the realloced array, then do changes there
entry_t* temp = calloc(newSize,sizeof(entry_t));
table->size = newSize;
//temp pointer to an entry
entry_t *tptr = NULL;
unsigned int pos = 0;
unsigned int index = 0;
while(pos != table->size){
tptr = &table->entries[pos];
if(tptr->exists == 1){
index = hashString(table->seed, tptr->value, table->size, pos);
temp[index] = *entryInit(tptr->value);
temp[index].occurence = tptr->occurence;
break;
}
else pos++;
}
table->entries = temp;
//TODO: change table destroy to free the previous array from the table
free(temp);
return table;
}
//insert works fine, it is efficient enough to add something in the table
unsigned int tableInsert(table_t* table,const char* const value){
//decide when to resize, might create a large enough array to bloat the memory?
if(table->usedEntries >(unsigned int)(2*(table->size/3))) table = tableResize(table, table->size*2);
entry_t* entry = NULL;
unsigned int index;
auto int position = 0;
while(position != table->size){
//calculate the hash of our string as a function of the current position on the table
index = hashString(table->seed,value,table->size, position);
entry = &table->entries[index];
if(entry->exists == 0){
*entry = *entryInit(value);
table->usedEntries++;
return index;
} else if (entry->exists == 1 && strcmp(entry->value, value) == 0){
entry->occurence++;
return index;
} else{
position++;
}
}
}
//there might be an issue here
static inline void tableDestroy(const table_t* const table){
entry_t* entry = NULL;
for (auto int i = 0; i < table->size; ++i){
entry =&table->entries[i];
//printf("Value: %s Occurence: %d Exists: %d \n",entry->value, entry->occurence, entry->exists );
if(&table->entries[i] !=NULL)free(&table->entries[i]);
}
free(table);
}
entities.h :
#pragma once
typedef struct __attribute__((packed)) __entry {
char *value;
unsigned int exists : 1;
unsigned int occurence;
} entry_t;
typedef struct __table {
int size;
int usedEntries;
entry_t *entries;
unsigned int seed;
} table_t;
here is how I read from a file and process the text:
void readFromFile(const char* const fileName, table_t* table){
FILE *fp = fopen(fileName, "r");
if(!fp) fprintf(stderr,"error reading file. \n");
char word[15];//long enough to hold the biggest word in the text?
int position = 0;
char ch;
while((ch = fgetc(fp))!= EOF){
//discard all the ascii chars that are not letters
if(!(ch >= 65 && ch <= 90) && !(ch >= 97 && ch <= 122)){
word[position]= '\0';
if(word[0] == NULL)continue;
tableInsert(table, word);
position = 0;
continue;
}
else word[position++] = ch;
}
}
Any suggestions what is wrong with my code?
I believe resize might have an issue and I am not properly deleting yet because I have had a lot of problems with the memory management.
Thanks in advance!
I am not very skilled at C, especially the dynamic allocation bit of C and I´ve encountered this strange problem. Background is that I have to read input from a user, save it into struct that I defined like this:
typedef struct
{
int camera_ID;
int month;
int day;
int hour;
int min;
char rz[1001];
} cameraEntry;
and then save that struct into an array. Everything works fine, I am able to read the data, create said struct but when it comes to saving it into the array it crashes. I´ve tried assignign the values one by one and found out that the char array causes problems. I´ve tried assigning it char by char but there must be something else I am missing. Here is the code for reading and saving the user input and my main function:
int readEntry(cameraEntry **entries, int *maxN)
{
int n = 0, last = 0;
char brace;
*entries = malloc(*maxN * sizeof(cameraEntry *));
if (scanf("%c", &brace) != 1 || brace != '{')
return -1;
do
{
if (n >= *maxN)
{
*maxN = *maxN * 2;
*entries = realloc(*entries, *maxN * sizeof(cameraEntry *));
}
cameraEntry read = parseInput(&last);
if (read.camera_ID < 0)
return -1;
(*entries)[n].camera_ID = read.camera_ID;
(*entries)[n].month = read.month;
(*entries)[n].day = read.day;
(*entries)[n].hour = read.hour;
(*entries)[n].min = read.min;
//Without this line of code it works like charm
strcpy((*entries)[n].rz, read.rz);
n++;
} while (last == 0);
return n;
}
int main(void)
{
cameraEntry *entries = NULL;
int maxN = 2;
int n = readEntry(&entries, &maxN);
if (n < 0)
{
printf("Wrong input\n");
free(entries);
return 1;
}
printf("Entry count: %d\n", n);
free(entries);
return 0;
}
So please, if you can find the mistake in my code and explain why is it happening I would be very grateful.
I am actually trying to implement a breadth-first-search algorithm in C, as an input I take any graph from a file and store all nodes and vertices in a structure.
Then I create an adjacency matrix, and run through all columns, push encountered nodes on a stack, pop them and so on till I have all the paths.
Still I have problems storing those paths in a linked list, and by problem I mean that sometimes, from some specific cases, I lose the last value of my stored path (one int array per link), which is quite surprising as it occurs only on paths of length 5 (I cannot test all lengths but up to 12 it seems OK).
It's weird, because these values are lost at function exit (I tried debugging using LLDB and in the function that creates the link, the last byte exists, but once I leave the function, it does not) and not all the time (1 out 10 execution all is fine).
To me this is a malloc issue, so I checked every single malloc of my program in order to solve (unsuccessfully) the problem. Checked all the variables and all seems fine, except for this 5 length case (I assume my program has a 'defect' that is only apparent in this case, but why ?).
I would gladly accept some help, as I just ran out of things to check.
Here is the code of the main BFS function :
void bfs(t_lemin *e)
{
t_path *save;
//set needed variables
set_bfs_base_var(e);
save = e->p;
while (paths_remain(e))
{
//Special Start-End case
if (e->map[e->nb_start][e->nb_end] == 1)
{
create_single(e);
break ;
}
e->x = e->nb_start;
reset_tab(e);
while (e->x != e->nb_end)
{
e->y = 0;
while (e->y < e->nb_rooms)
{
if (e->map[e->x][e->y] == 1 && !e->visited[e->y])
##push_on_stack the nodes
push_stack(e);
e->y++;
}
//go_to first elem on stack
e->x = e->stack[0];
if (e->x == e->nb_end || is_stack_empty(e->stack, e->nb_rooms - 1))
break ;
e->visited[e->x] = 1;
//set_it as visited than pop it
pop_stack(e, e->nb_rooms);
}
if (is_stack_empty(e->stack, e->nb_rooms - 1))
break ;
e->find_new[add_path(e)] = 1;
discover_more_paths(e, save);
}
print_paths(e, save);
e->p = save;
}
And here the 2 functions that stores the paths in a linked list :
void create_path(t_lemin *e, int *pa, int len)
{
int j;
j = 1;
//create_new_node if required
if (e->p->path)
{
if (!(e->p->next = malloc(sizeof(t_path))))
return ;
e->p = e->p->next;
}
//create_the_array_for_path_storing
e->p->path = malloc(sizeof(int) * len + 2);
e->p->next = NULL;
e->p->size_path = len + 2;
//copy_in_it
while (--len >= 0)
{
e->p->path[j++] = pa[len];
}
//copy_end_and_start_at_end_and_start
e->p->path[e->p->size_path - 1] = e->nb_end;
e->p->path[0] = e->nb_start;
e->nb_paths++;
}
int add_path(t_lemin *e)
{
int i;
int save;
int *path;
int next_path;
i = 0;
if (!(path = malloc(sizeof(int) * e->nb_rooms)))
exit(-1);
save = e->nb_end;
//in_order_to_save_the_path_i store the previous value of each node so I can find the path by iterating backward
next_path = -1;
while (e->prev[save] != e->nb_start)
{
path[i] = e->prev[save];
save = e->prev[save];
next_path = next_path == -1 && get_nb_links(e, path[i])
> 2 ? path[i] : -1;
i++;
}
//path_contains all values of the path except for start and end
save = i;
while (i < e->nb_rooms)
{
path[i] = 0;
i++;
}
create_path(e, path, save);
i = next_path == -1 ? path[0] : next_path;
//ft_printf("to_block : %d\n", i);
return (next_path == -1 ? path[0] : next_path);
}
If needed here is a clone of the entire repository, the issue can be seen running the program with maptest in the main directory : https://github.com/Caribou123/bfs_agesp.git
Make && ./lem_in < maptest
All paths must end by the last room, whereas in this case the value of the last room becomes 0. So the program outputs "start->room1->room2->....->start as the index value of start is 0.
Here is a look at my 'e', the main structure. (it's quite huge, don't be scared) :
typedef struct s_lemin
{
int x;
int y;
char *av;
int nb_ants;
int st;
int nd;
int nb_rooms;
int nb_paths;
int max_sizep;
int nb_links;
int nb_start;
int nb_end;
int **map;
int *stack;
int *visited;
int *prev;
int *find_new;
int maxy;
int maxx;
int minx;
int conti;
int miny;
char ***saa;
struct s_rooms *r;
struct s_ants *a;
struct s_rooms **table_r;
struct s_links *l;
struct s_hash **h;
struct s_rooms *start;
struct s_rooms *end;
struct s_info *i;
struct s_path *p;
struct s_path *select_p;
}
Thank you in advance for your help, and sorry if it's some stupid malloc that I somehow missed.
Artiom
I am trying to improve my C skills so I apologize if my question is long. I am having a hard time understanding as to why my struct pointer holds the wrong value in my program, I tried to debug it but I am still relatively new to C and was hoping one of you could tell me what I'm doing wrong here and how I could improve my code and what to focus on.
I am making a program that stores user data on this struct and then prints it out.
typedef struct table {
char *firstName;
char *lastName;
int id;
}USER;
This function below stores the first name
void firstName(int *counter, int *check, USER *pt) {
for (int i = *counter; i < *check; i++) {
pt[i].firstName = calloc (MAX_LENGTH, sizeof(pt));
printf("Enter First Name: ");
getchar();
fgets(pt[i].firstName, MAX_LENGTH, stdin);
}
}
This is just my bool function returning true or false
bool isTrue(char *decision) {
if(*decision == 'Y') {
return true;
}
else {
return false;
}
}
And this is my main
int main(int argc, char **argv) {
USER *pt = calloc(1, sizeof(pt));
int counter = 0, check = 0;
char decision = '\0';
while (1) {
printf("Would you like to enter a user?(Y/N):");
fgets(&decision, 2, stdin);
strtok(&decision, "\n"); //remove the newline char
if (!isTrue(&decision)) {
break;
}
if (counter != 0) {
pt = realloc(pt, sizeof(pt) * 10); //the 10 is temporary
}
check = counter + 1; // make sure loop only runs once.
firstName(&counter, &check, pt);
++counter; // increment counter;
}
printStruct(pt, &counter);
return 0;
}
When I run it out sometimes it works fine and returns everything and sometimes it skips a value. This is what I get. It skips the value at pointer index 1 and prints garbage instead.
Would you like to enter a user?(Y/N):N
First name at array 0 is Ermir
First name at array 1 is P#1First name at array 2 is Kevin
First name at array 3 is Blaus
First name at array 4 is Adam
Also I was wondering why is it when I realloc here If i do I get a realloc error when I enter the second name.
if (counter != 0) {
pt = realloc(pt, sizeof(pt) * 10); //realloc(pt, sizeof(pt) * counter + 1) wont work
}
char decision = '\0';
...
fgets(&decision, 2, stdin);
You are only allocating 1 char but are at least reading 2 chars into it. Fix by allocating a sufficiently sized array for decision.
Unrelated but in firstName() pt[i].firstName = calloc (MAX_LENGTH, sizeof(pt)); should be pt[i].firstName = calloc (MAX_LENGTH, 1);
I'm working on a homework assignment and I need to basically create a character buffer. One of the functions I need to create is called "b_reset". It's purpose is to reinitialize the given buffer so that it will point to the first position in the char buffer. This is needed because later on, when a new char is added to the buffer, it needs to be added to the first position in the buffer.
This is the code I have thus far:
The struct:
typedef struct BufferDescriptor {
char * ca_head ;
int capacity ;
char inc_factor;
int addc_offset ;
int mark_offset ;
char r_flag;
char mode;
} Buffer ;
The code:
int b_reset ( Buffer *pB )
{
Buffer *temp = NULL;
int i = 0;
int j = 1;
if (pB == NULL)
{
return R_FAIL_1;
}
else
{
temp = (Buffer*)malloc(sizeof(Buffer*));
if (temp == NULL)
{
return R_FAIL_1;
}
temp->ca_head = (char*)malloc(pB->capacity);
if (!temp->ca_head)
{
temp = NULL;
return R_FAIL_1;
}
for(i = 0;i < ca_getsize(pB);++i)
{
temp->ca_head[j] = pB->ca_head[i];
j++;
}
pB->ca_head = temp->ca_head;
//free(temp->ca_head);
//free(temp);
return 0;
}
}
My goal in this code was to create a temporary buffer that would basically shift over everything 1 time based on the actual given buffer. This would make the first position empty so another char could be added.
The problem I'm running into is that the original buffer doesn't seem to be returning the right values after I reset it.
When I do this for example:
temp->ca_head[0] = 'a';
temp->ca_head[1] = 'b';
temp->ca_head[2] = 'c';
temp->ca_head[3] = 'd';
temp->ca_head[4] = 'e';
b_reset(temp); //this will return the size as 0, when it's actually 5
//temp->ca_head[0] = 'i'; //if this is executed, it returns the size as 6
//and prints out the right values, but if it's not,
//it will not print out anything
printf("%d", ca_getsize(temp));
for(i = 0;i < ca_getsize(temp);++i)
{
printf("%c", temp->ca_head[i]);
}
I know something is going wrong here, but I'm not too sure what. Any suggestions would be greatly appreciated.
This code is based on your followup comment:
well I'm not trying to resize the buffer, I just want to create an
empty space in the first position, so basically shifting everything to
the right 1 time. The assumption is that there is a enough space in
the buffer to handle this process.
I don't think you need to do any malloc() ing beyond the initial one. You can just shift everything up in a loop:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <assert.h>
#define R_FAIL_1 1
#define BUFFER_SIZE 10
typedef struct BufferDescriptor {
char * ca_head ;
int capacity ;
char inc_factor;
int addc_offset ;
int mark_offset ;
char r_flag;
char mode;
} Buffer ;
void allocate_buffer(Buffer *pB, int size)
{
pB->ca_head = malloc(size);
assert(pB->ca_head);
pB->capacity = size;
}
int ca_getsize( Buffer *pB)
{
return pB->capacity;
}
int b_reset ( Buffer *pB )
{
int i = 0;
if (pB == NULL)
{
return R_FAIL_1;
}
else
{
if ( ca_getsize(pB) <= 0 || pB->ca_head == NULL )
return R_FAIL_1;
}
// shift data up by 1 byte
for( i = ca_getsize(pB) - 1 ; i > 0;i-- )
{
pB->ca_head[i] = pB->ca_head[i-1];
}
pB->ca_head[0] = '\0';
return 0;
}
void print_buffer(Buffer *pB)
{
printf("capacity: %d \n", ca_getsize(pB));
for (int i = 0;i < ca_getsize(pB);++i)
{
printf("buffer(%d): [%d] ",i, pB->ca_head[i]);
}
printf("\n");
}
int main(void)
{
Buffer a_buffer;
allocate_buffer(&a_buffer,BUFFER_SIZE);
strcpy(a_buffer.ca_head,"abcdefgh");
print_buffer(&a_buffer);
int ret = b_reset(&a_buffer);
assert(ret == 0);
print_buffer(&a_buffer);
}
temp = (Buffer*)malloc(sizeof(Buffer*));
You need to allocate enough space to hold a Buffer, but you only allocate enough space to hold a pointer to a buffer. This should be:
temp = (Buffer*)malloc(sizeof(Buffer));
You are managing your memory incorrectly. You are allocating memory for a new Buffer struct when actually you only need to handle the memory of the ca_head member (if my interpretation of your homework problem is correct).
Each time you invoke b_reset, you will allocate memory for this struct that will not be released. If you don't handle your memory correctly, you will experience unexpected results as the one you are reporting in your question.
I suggest you to make a research on the function realloc and use it properly in your b_reset function.
Good luck with your homework.