S
somebody
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.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.field1 != NULL; i++) {
if(strcmp(field1, mystruct.field1) == 0) {
return(mystruct.numfield);
}
/*THIS SEGFAULTS ALWAYS!!!!*/
/*if (strcmp(mystruct.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,
};
In the for loop in search.c, the for loop never exits,
even if mystruct.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.field1 != NULL; i++) {
if(strcmp(field1, mystruct.field1) == 0) {
return(mystruct.numfield);
}
/*THIS SEGFAULTS ALWAYS!!!!*/
/*if (strcmp(mystruct.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,
};