Why segfault and no NULL match in for loop?



There are two files below named search.c and search.h.
In the for loop in search.c, the for loop never exits,
even if mystruct[i].field1 has no match. Instead of
exiting the for loop it keeps going until it segfaults.
This seems to be related to the strcmp with the NULL
value. There are 2 comments below that indicate
the segfaults. I guess the question is, when there
is no match, how to I detect that and return without
a segfault?

-Thanks


SEARCH.C ----------------------------------------

#include <string.h>
#include <stdlib.h>
#include <stdio.h>

#include "search.h"


int search(char * field1)
{
int i = 0;


/* This is never = to NULL, even when no match for field1 */

for(i=0; mystruct[i].field1 != NULL; i++) {

if(strcmp(field1, mystruct[i].field1) == 0) {
return(mystruct[i].numfield);
}


/*THIS SEGFAULTS ALWAYS!!!!*/
/*if (strcmp(mystruct[i].field1, NULL) == 0) {*/
/*}*/

}

return(0);
}



int main(void)
{
int retval = 0;

/* THIS CAN CAUSE SEGFAULT TOO!!! */
/*This works if you match, for example, CCC. But if*/
/*you change the CCC to say YYY, which is not in the*/
/*struct, it segfaults.*/

char str[] = "CCC";

retval = search(str);

printf("retval = %d\n", retval);

return 0;
}


SEARCH.H -----------------------------


struct _mystruct
{
char field1[4];
char field2[4];
char field3[2];
char field4[3];
int numfield;
};


struct _mystruct mystruct[] =
{
"AAA", "EEE", "R", "DF", 25,
"BBB", "FFF", "R", "DF", 25,
"CCC", "GGG", "R", "DF", 99,
"DDD", "HHH", "R", "DF", 13,
};
.



Relevant Pages

  • Re: Bits to Byte
    ... character data to sets of 13 bits each and then further convert ... int encode_width, int *output) ... /* shift everything over by the appropriate amount; ... Some manual loop unrolling to the point where the number of bits processed ...
    (comp.programming)
  • Re: Bits to Byte
    ... character data to sets of 13 bits each and then further convert ... int encode_width, int *output) ... then, "and" with the mask; ... Some manual loop unrolling to the point where the number of bits processed ...
    (comp.programming)
  • Re: stop application
    ... input seems to be an int or char, ... > But the main problem still exists: I'm reading data from a serial port. ... the while loop runs in the ...
    (comp.lang.c)
  • Re: is there a better way to optimise this code
    ... the first XOR on a short int at RGBand the second on a char at RGB. ... an array+offset but rather set a pointer to the base before you enter ... the loop and increment it. ...
    (comp.lang.c)
  • Re: Problem with character string loop and strlen()
    ... >I have a function which requires me to loop from the end of a string to ... >the beginning on a char by char basis: ... >int foo ... a warning anything like that. ...
    (comp.lang.c)