Reputation: 411
So, basically the code at the end of this post is my first try to implement some parallels queues.
I created the structures "fila1" and "fila2" using the same function createBase() which allocates memory space with "malloc".
Both structures were created in the same way and seems to be created correctly. However, the function prints "hellou" , but doesn't print "hi", both should be printed.
Tried to debug, and realized when my program enters inside the "while" loop, the second "fila2" changes its memory address, also its child's value, they no longer point to "NULL". I don't understand why. "fila1" still works as it should.
Just to illustrate, before while loop (working fine!):
After the program go past the while loop line (oh no!):
Oh, almost forgot, here is the code. I used as input command = "a".
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
struct Member {
struct Member *next;
};
struct Base{
struct Member *begin, *end;
};
//Funcoes
struct Base* createBase(){
struct Base *new;
new = (struct Base*)malloc(sizeof(struct Base));
if (new != NULL) {
new->begin = NULL;
new->end = NULL;
}
return new;
};
int main(void) {
char command[1];
struct Base *fila1, *fila2;
struct Base *createBase();
fila1 = createBase();
fila2 = createBase();
while(scanf("%s", &command) != EOF) {
if (fila1->begin == NULL) {
printf("hellou");
}
if (fila2->begin == NULL) {
printf("hi");
}
}
return 0;
}
Upvotes: 0
Views: 156
Reputation: 504
As @tkausl and @ilkkachu commented before, the command array is too small to contain the command itself. Even if your commands are only 1 character long (you say that you entered as command "a"), remember that the buffer will contain at least two bytes: one for the command character itself ('a') and another one for the '\0' (a char with value 0) terminating the string.
Probably scanf is storing 'a' at command[0] and trying to store the terminating '\0' at command[1] which doesn't exist (because command contains only 1 byte). This '\0' is probably overflowing command and overwriting the last byte of fila2 (note that it changes from 0xd0 to 0x00, which is exactly the value of '\0').
You should add one byte to command to accomodate the '\0' (so making it "at least" char command[2]) although I would recommend using more secure user input methods, such as fgets (which requires you to indicate the buffer size and thus would never overflow).
Upvotes: 1
Reputation: 9570
The first condition fila1->begin == NULL
tests whether the begin
membes is NULL
– and it is, hence the printout appears.
The second one fila2->begin = NULL
assigns NULL
to the begin
member, and then the result of this assignment is converted into integer, as required by if()
. The integer result of the conversion is zero, which means 'false', and so the second printout does not take place.
Upvotes: 1