Forums
New posts
Search forums
Members
Current visitors
Log in
Register
What's new
Search
Search
Search titles only
By:
New posts
Search forums
Menu
Log in
Register
Install the app
Install
Forums
Archive
Archive
C Programming
Why segfault and no NULL match in for loop?
JavaScript is disabled. For a better experience, please enable JavaScript in your browser before proceeding.
You are using an out of date browser. It may not display this or other websites correctly.
You should upgrade or use an
alternative browser
.
Reply to thread
Message
[QUOTE="somebody, post: 2873659"] 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, };[/i][/i][/i][/i][/i] [/QUOTE]
Verification
Post reply
Forums
Archive
Archive
C Programming
Why segfault and no NULL match in for loop?
Top