Why segfault and no NULL match in for loop?
- From: somebody <some@xxxxxxxx>
- Date: Wed, 02 May 2007 18:47:09 -0400
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,
};
.
- Follow-Ups:
- Re: Why segfault and no NULL match in for loop?
- From: CBFalconer
- Re: Why segfault and no NULL match in for loop?
- From: Default User
- Re: Why segfault and no NULL match in for loop?
- From: Walter Roberson
- Re: Why segfault and no NULL match in for loop?
- Prev by Date: Re: debounce state diagram FSM
- Next by Date: Re: debounce state diagram FSM
- Previous by thread: C Ebooks, Itz my effort
- Next by thread: Re: Why segfault and no NULL match in for loop?
- Index(es):
Relevant Pages
|