3

I have this struct

typedef struct no
{
    char command[MAX_COMMAND_LINE_SIZE];
    struct no * prox;
} lista;

lista *listaCommand = NULL;

and I'm filling listaCommand with a simple function that seems to work ok, as I can read the values without any problem, but if I try to compare, like

strcmp(listaCommand->prox>command, ">")

I just get a segmentation fault, even though the value > is there, why this is happening?

Dante003
  • 55
  • 4
  • How do you initialize `lista`? And `lista->command`? – Lorenzo Dematté May 24 '13 at 07:24
  • 2
    Your are missing Correct it to -> strcmp(listaCommand->prox->command, ">") – Navnath Godse May 24 '13 at 07:24
  • @Navnath uhhh.. clever! I though it was a typo, but you are right, if this is the actual code it is a comparison and it returns either 0 or 1.. Nice! :) – Lorenzo Dematté May 24 '13 at 07:25
  • The fact that there's a problem in *this* code doesn't mean that's the only problem. @Dante003 Should Navnaths answer not solve your problem, please devise a minimal, **compilable** testcase using `strcmp` to produce your segfault. – autistic May 24 '13 at 07:29
  • Can anyone tell me how come nobody sees anything wrong with trying to dereference a **NULL** pointer?Either my basics are rusty or you are not seeing the elephant in the room!! – Rüppell's Vulture May 24 '13 at 07:37
  • @Rüppell'sVulture From what we can see, "I'm filling listaCommand with a simple function that seems to work ok". The OP *could* be inadvertently blinding us to other errors, which is why I asked for a minimal, compilable testcase... – autistic May 24 '13 at 07:44
  • Are you asking about the difference between the `>` operator and the `->` operator? – autistic May 24 '13 at 07:52

3 Answers3

10
strcmp(listaCommand->prox>command, ">") 

Should be

strcmp(listaCommand->prox->command, ">")


In your code listaCommand->prox>command will be seen as a comparison operation, using the > operator. A comparison in C returns an integer, 0 if false, non-zero otherwise. There are good chances it will return 0, which is not a valid memory address. Hence, the segmentation fault.

Lorenzo Dematté
  • 7,638
  • 3
  • 37
  • 77
Navnath Godse
  • 2,233
  • 2
  • 23
  • 32
0

Change

strcmp(listaCommand->prox>command, ">")

to

strcmp(listaCommand->prox->command, ">")
Ry-
  • 218,210
  • 55
  • 464
  • 476
Raghu Srikanth Reddy
  • 2,703
  • 33
  • 29
  • 42
0

Allocate memory !!!

typedef struct no
{
    char str[20];
    struct no * prox;
} lista;

lista *listaCommand = NULL;

int main(int argc, char** argv)
{
    listaCommand = malloc(sizeof(lista));
    listaCommand->prox = malloc(sizeof(lista));
    strcpy(listaCommand->prox->str, "aaa");
    printf("%d\n", strcmp(listaCommand->prox->str, ">>"));

    free(listaCommand->prox);
    free(listaCommand);

    return 0;
}
kundrata
  • 651
  • 3
  • 12
  • 24