I am kinda new to C and I am trying to write a simple snake remake.
You can view the source on github: https://github.com/blackwolf12333/Snake
When building there are no warnings or errors in the output. But when I run the executable and hit enter it exit's with "Segmentation fault(core dumped)".
I am not a pro yet with pointers, I come from java, and when googling I found that it probably is a problem with pointers.
I have no idea of where it is going wrong because for as far as I know I am doing things right. The problem is when I try to loop through my snake's body_part's.
void print_snake() {
int i;
body_part *next = main_snake.head.next;
move(main_snake.head.pos.x, main_snake.head.pos.y);
addch('$');
for(i = 0; i < main_snake.length; i++) { //TODO: segfaults when 'main_snake.length'(should be this) instead of 'main_snake.length - 1'
printf("1 part");
print_body_part(next);
next = next->next;
}
}
That's from the snake.c file in the repository.
I hope you guys can help me,
greetings blackwolf12333
Before going deep through the code it is obvious that when next becomes null and next->next causes segmentation fault.
In the loop you are starting at a node next to head(main_snake.head.next). Therefore in a list of 4 objects you are processing only 3 objects. In that case iterations should be 3 instead of 4 because main_snake.length counts the head also as shown in the function initialize_snake. That is why you are getting segmentation fault.
If you want to iterate over a chained list, don't use a seperate stop condition. Your i variable and main_snake.length are not necessary. You can replace
for(i = 0; i < main_snake.length; i++)
with
body_part *next;
for(next = main_snake.head.next; next->next != NULL; next=next->next){
...
}
Related
I'm trying to use realloc function in C, to dynamically operate on a char array of strings (char**).
I usually get a realloc():invalid old size error after 41st cicle of the for loop and I really can't understand why.
So, thanks to everyone who will help me ^-^
[EDIT] I'm trying to make the post more clear and following your advices, as a "new active member" of this community, so thank you all!
typedef struct _WordsOfInterest { // this is in an header file containing just
char **saved; // the struct and libraries
int index;
} wordsOfInterest;
int main() {
char *token1, *token2, *save1 = NULL, file[LEN], *temp, *word, **tokenArr;
int n=0, ch,ch2, flag=0, size, init=0,position,currEdit,init2=0,tempEdit,size_arr=LEN,
oldIndex=0,totalIndex=0,*editArr,counterTok=0;
wordsOfInterest toPrint;
char **final;
toPrint.index = 0;
toPrint.saved = malloc(sizeof(char*)*LEN);
editArr = malloc(sizeof(int)*LEN);
tokenArr = malloc(sizeof(char*)*LEN);
final = malloc(sizeof(char*)*1);
// external for loop
for(...) {
tokenArr[counterTok] = token1;
// internal while loop
while(...) {
// some code here surely not involved in the issue
} else {
if(init2 == 0) {
currEdit = config(token1,token2);
toPrint.saved[toPrint.index] = token2;
toPrint.index++;
init2 = 1;
} else {
if((abs((int)strlen(token1)-(int)strlen(token2)))<=currEdit) {
if((tempEdit = config(token1,token2)) == currEdit) {
toPrint.saved[toPrint.index] = token2;
toPrint.index++;
if(toPrint.index == size_arr-1) {
size_arr = size_arr*2;
toPrint.saved = realloc(toPrint.saved, size_arr);
}
} else if((tempEdit = config(token1,token2))<currEdit) {
freeArr(toPrint, size_arr);
toPrint.saved[toPrint.index] = token2;
toPrint.index++;
currEdit = tempEdit;
}
}
}
flag = 0;
word = NULL;
temp = NULL;
freeArr(toPrint, size_arr);
}
}
editArr[counterTok] = currEdit;
init2 = 0;
totalIndex = totalIndex + toPrint.index + 1;
final = realloc(final, (sizeof(char*)*totalIndex));
uniteArr(toPrint, final, oldIndex);
oldIndex = toPrint.index;
freeArr(toPrint,size_arr);
fseek(fp2,0,SEEK_SET);
counterTok++;
}
You start with final uninitialized.
char **final;
change it to:
char **final = NULL;
Even if you are starting with no allocation, it needs a valid value (e.g. NULL) because if you don't initialize a local variable to NULL, it gets garbage, and realloc() will think it is reallocating a valid chunk of memory and will fail into Undefined Behaviour. This is probably your problem, but as you have eliminated a lot of code in between the declaration and the first usage of realloc, whe cannot guess what is happening here.
Anyway, if you have indeed initialized it, I cannot say, as you have hidden part of the code, unlistening the recommendation of How to create a Minimal, Reproducible Example
.
There are several reasons (mostly explained there) to provide a full but m inimal, out of the box, failing code. This allows us to test that code without having to provide (and probably solving, all or part) the neccesary code to make it run. If you only post a concept, you cannot expect from us complete, full running, and tested code, degrading strongly the quality of SO answers.
This means you have work to do before posting, not just eliminating what you think is not worth mentioning.
You need to build a sample that, with minimum code, shows the actual behaviour you see (a nonworking complete program) This means eliminating everything that is not related to the problem.
You need (and this is by far more important) to, before sending the code, to test it at your site, and see that it behaves as you see at home. There are many examples that, when eliminated the unrelated code, don't show the commented behaviour.
...and then, without touching anymore the code, send it as is. Many times we see code that has been touched before sending, and the problem dissapeared.
If we need to build a program, we will probably do it with many other mistakes, but not yours, and this desvirtuates the purpose of this forum.
Finally, sorry for the flame.... but it is necessary to make people read the rules.
img of error
Above is an error I have been getting, in relation to this line in my program:
storedData[k] = min(dist[index1][k],dist[index2][k]);
Now here is the surrounding functions to this line:
for(int k = 0; k <arraySize; k++){
if(k!= index1 && k != index2){
if(method == SINGLE_LINKAGE){
storedData[k] = min(dist[index1][k],dist[index2][k]);
} else {
storedData[k] = max(dist[index1][k],dist[index2][k]);
}
}
}
Now after playing around with it for quite a while, I realised that the issue it has is with the incrementing 'k' variable in the for loop. More specifically it is worried that when used as an index in dist, the value returned will be uninitialised. Now in terms of functionality, my program works fine and does everything I want it to do. More notably, I have also initialised this function elsewhere in a helper function which is why this confuses me more. I have initialised all the values from index 0-arraysize which in my head means this should never be an issue. Im not sure if maybe this is caused because its done outside of the main function or something. Regardless it keeps giving me grief and I would like to fix it.
You need to work back from the error to its origin. Even if you are initializing your arrays, it is possible that something is 'uninitializing' them again afterwards. memcheck does not flag uninitialized data when it is copied, only when it affects the outcome.
So in pseudo-code you might have
Array arr;
Scalar uninit; // never initialized
init_array(arr);
// do some stuff
arr[3] = uninit; // no error here
for (i = 1 to arr.size)
store[i] = max(arr[i], arr[i-1]; // errors for i == 3 and 4
There are two things that you could try. Firstly, try some 'printf' debugging, something like
for(int k = 0; k <arraySize; k++) {
if(k!= index1 && k != index2) {
fprintf(stderr, "DEBUG: k %d index1 %d index2 %d\n", k, index1, index2);
// as before
Then run Valgrind without a log file. You should then be able to see which indices cause the error(s).
Next, try using ggbserver. Run valgrind in one terminal with
valgrind --vgdb-error=0 prog args
and then run gdb in a second terminal to attach (see the text that is output in the 1st terminal for the commands to use).
You can then use gdb as usual (except no 'run') to control your guest app, with the additional ability to run valgrind monitor commands.
I have written a program and I have created this structure
struct position_found
{
int row;
int column;
struct position_found *next;
};
typedef struct position_found position_found, *position_found_ptr;
and then i use this function to create a new node type position_found
position_found_ptr new_position_found_node(int row, int column)
{
position_found_ptr x;
x=(position_found_ptr)malloc(sizeof(position_found));
if(x==NULL)
{
printf("out of memory");
exit(2);
}
x->row=row;
x->column=column;
x->next=NULL;
return x;
}
The problem is that x=(position_found_ptr)malloc(sizeof(position_found)); presents seg fault, but if i print something right before this, for example printf("k");, malloc will work properly and my program will continiue. I've tried using the function on her own in a test programm and it works perfectly. Do you have any idea what is happening?
if you want , put your whole code so i can debug it with gdb (or you can do it yourself ) :D
but the answer for your second question :
the reason is that when you run a program , in has some memory size (except your variables and other things ) its about OS !
if you have a problem with working with memory (like your code) you get segmentation fault !
but when you add some line(s) of code ,this changes the data order writing in memory cells so that your remaining code doesn't write on illegal memory cells ! :D
for example :
if before adding printf("k"); you were on x1234 which is illegal and because of that you've got seg fault , after adding that , you went on x4323 so this is legal and everything is ok :D
you can use "gdb" to "disassemble" to check what i said :D !!
I am trying to print out the contents of a 2 dimensional array starting from a certain location in the array (since not all elements of the array are filled). The array contains pointers to a data structure I created called a node. Here is the print code:
void repository_print(int print_elements){
node *travTemp;
travTemp = main_list[highest_level][0];
while((travTemp->down)!=NULL){
while((travTemp->next)!=NULL){
printf(" {%d, %d}", travTemp->key, travTemp->d);
travTemp = travTemp->next;
}
travTemp = travTemp->down;
printf("\n");
}
}
Basically the array holds pointers to node elements in a sorted fashion. Each node contains a "key" attribute and a "d" attribute and I am just trying to go level by level and print out the {key, d} records cleanly. I keep getting a segfault when I call the print command in my main. I tried using gdb to debug it but it won't give me an actual line. It just says:
#0 0x0000000000400b2e in repository_print ()
#1 0x0000000000400722 in main ()
Does anyone how I can find the seg fault or why the seg fault is occurring? Thanks.
EDIT:
I did try compiling with -g and found that the error is occurring at the line "while((travTemp->next)!=NULL)". This is confusing to me because this attribute should not be NULL. I'll have to check the rest of my code. The main_list declaration is as follows in case anyone needs to know:
node *main_list[MAX_HEIGHT][MAX_LEVEL];
EDIT:
So following Felipe's advice I changed my print function to the following:
node *travTemp;
travTemp = main_list[highest_level][0];
while(travTemp!=NULL && (travTemp->down)!=NULL){
printf(" {%d, %d}", travTemp->next->key, travTemp->next->d);
travTemp = travTemp->next;
}
travTemp = main_list[highest_level+1][0];
printf("\n");
However, now, I'm getting a seg fault at the print statement line. If travTemp->next does not equal NULL what's the problem with travTemp->next->key? I have no idea why since these values should exist in the repository.
If main_list[highest_level][0] is NULL, then your initial attempt to test travTemp->next will fail. #Filipe has addressed getting more debugging info in the comments.
Update: if it isn't NULL but following travTemp seems to be the problem, perhaps it is some other illegal value. Not seeing how main_list was filled, can't say more than that.
I am creating a program in c which is based on a linked list, where every node (of struct) holds an integer and a pointer to the next node.
I use dynamic allocation (malloc) and deallocation (free) as new nodes are added and old nodes are deleted.
when a node is deleted a function named delete is called.
I discovered that the program crashes sometimes when this delete-function is called and I KNOW that its something with the pointers in the method but I dont know WHERE in the code (row number) and WHY this happends.
I am used to high-level languages such as Java and I am used to encircle the problem by putting print-syntax at certain places in the method just to reveal WHERE it crashes.
I thought I could do the same with c and with pointer because to my knowledge I beleive the code is read from top to bottom that is 1, 2, 3, 4, and so on. (maybe interrupt handlers behave another way?)
So in this function named delete I have gone so far by putting this printf() at the very beginning of the delete-function - and all the same the program crashes.
So my Question - is it really possible that its some syntax in the delete-function (when I loop pointers for instance) that causes the crash WHEN not even the printf() is printing?
Am I wrong when I believe that the program is executed from to to bottom - that is 1, 2, 3 ....
You can se my printf-function in the very beginning of delete-function
And by the way - how could I solve this problem when I get this cryptic crash message from windows? See the bitmap!!
Greatful for answers!!!
int delete(int data) {
printf("IN THE BEGINNING OF DELETE!!!");
int result = 0;
if (queueref.last != NULL) {
node *curr_ptr;
node *prev_ptr;
node *temp_ptr;
if (queueref.first->data == data) {
temp_ptr = queueref.first;
queueref.first = queueref.first->next;
destroy_node(temp_ptr);
result = 1;
if (queueref.first == NULL) {
queueref.last = NULL;
puts("queue is now empty!!!");
}
} else {
prev_ptr = queueref.first;
curr_ptr = queueref.first->next;
printf("prev_ptr: %d\n", prev_ptr);
printf("curr_ptr: %d\n", curr_ptr);
while(curr_ptr != NULL) {
if (curr_ptr->data == data) {
result = 1;
if (curr_ptr->next != NULL) {
temp_ptr = curr_ptr;
destroy_node(temp_ptr);
prev_ptr->next = curr_ptr->next;
} else {
temp_ptr = curr_ptr;
queueref.last = prev_ptr;
prev_ptr->next = NULL;
destroy_node(temp_ptr);
}
}
curr_ptr = curr_ptr->next;
prev_ptr = prev_ptr->next;
}
}
}
return result;
}
Common mistake, here's the deal. This
printf("IN THE BEGINNING OF DELETE!!!");
needs to be
printf("IN THE BEGINNING OF DELETE!!!\n");
^^ note the newline
The reason is because stdio does not flush stdout until it sees a newline. If you add that newline, you should see the printf when the code enters the function. Without it, the program could crash, the stdout buffer would not have been flushed and would not see the printf.
Your code seems to have lots of implementation flaws. As a general advice I would recommend using some standard well-tested queue support library and static code analyzers (in this case you would even find dynamic analyzer valgrind very helpful, I guess).
For example, if implementation of destroy_node(ptr) is equivalent to free(ptr), then your code suffers from referencing destroyed data (or ,in other words, garbage) in this code snippet:
while(curr_ptr != NULL) {
if (curr_ptr->data == data) {
result = 1;
if (curr_ptr->next != NULL) {
temp_ptr = curr_ptr;
destroy_node(temp_ptr);
prev_ptr->next = curr_ptr->next; //<- curr_ptr is still in stack
//or register, but curr->next
//is garbage
// what if curr_ptr is first node? did you forget to update queueref.first?
} else {
temp_ptr = curr_ptr;
queueref.last = prev_ptr;
prev_ptr->next = NULL;
destroy_node(temp_ptr);
}
// if you you need to destroy only one node - you can leave the loop here with break;
}
curr_ptr = curr_ptr->next; /// assigning garbage again if node is found
prev_ptr = prev_ptr->next;
The reason why using destroyed data can work in * most * (if I can say that, basically this is unpredictable) cases is that the chances that this memory can be reused by other part of program for dynamically allocated data can vary on timings and code flow.
PS
Regarding cryptic messages in the Windows box - when program crashes OS basically generates crashdump and prints registers (and dumps some relevant memory parts). Registers and memory dumps can show the place of crash and immediate register/stack values but you have to now memory map and assembler output to understand it. Crashdump can be loaded to debugger (WinDbg) together with unstripped binary to check stactrace and values of local variables at the moment of crash. All these I described very very briefly, you could find tons of books / guides searching for "windows crash or crashdump analysis"