Thread: string compare “EXC_BAD_ACCESS”.

  1. #1
    Registered User
    Join Date
    Apr 2010
    Posts
    51

    string compare “EXC_BAD_ACCESS”.

    this code
    Code:
    #include <stdio.h>
    #include <string.h>
    
    int main(){
    	char *str1 = "A";
    	char *str2 = "A";
    	char *str3 = "!";
    	
    	printf("\n str1  =  %s", str1);
    	printf("\n str2  =  %s", str2);
    	printf("\n str3  =  %s", str3);
    	
    	printf("\nstrcmp(str1, str2) = %d", strcmp(str1, str2));
    	printf("\nstrcmp(str1, str3) = %d", strcmp(str1, str3));
    	printf("\nstrcmp(str3, str1) = %d", strcmp(str3, str1));
    	
    	if (strcmp(str1,str2) == 0) {
    		printf("\n%s is equal to %s", str1, str2);
    	}//if
    	
    	if (strcmp(str1, str3) > 0) {
    		printf("\n%s is greater than %s", str1, str3);
    	}//if
    	
    	if (strcmp(str3, str1 < 0)) {
    		printf("%s is less than %s", str3, str1);
    	}//if
    	
    	return 0;
    }//main

    gives this output:

    Code:
     str1  =  A
     str2  =  A
     str3  =  !
    strcmp(str1, str2) = 0
    strcmp(str1, str3) = 32
    strcmp(str3, str1) = -32
    A is equal to A
    Program received signal:  “EXC_BAD_ACCESS”.
    sharedlibrary apply-load-rules all
    the second "if" statement is not reached and I am unsure why?

  2. #2
    and the Hat of Guessing tabstop's Avatar
    Join Date
    Nov 2007
    Posts
    14,336
    You have "str1 < 0" as the second argument to strcmp, which is a bad thing.

  3. #3
    Registered User
    Join Date
    Apr 2010
    Posts
    51
    rats!

    ok, thanks.

  4. #4
    and the hat of int overfl Salem's Avatar
    Join Date
    Aug 2001
    Location
    The edge of the known universe
    Posts
    39,659
    Does your compiler complain (or can it, if you bump the warning level?)

    $ gcc -Wall foo.c
    foo.c: In function ‘main’:
    foo.c:25: warning: null argument where non-null required (argument 2)
    foo.c:25: warning: null argument where non-null required (argument 2)
    If you dance barefoot on the broken glass of undefined behaviour, you've got to expect the occasional cut.
    If at first you don't succeed, try writing your phone number on the exam paper.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Inheritance Hierarchy for a Package class
    By twickre in forum C++ Programming
    Replies: 7
    Last Post: 12-08-2007, 04:13 PM
  2. Program using classes - keeps crashing
    By webren in forum C++ Programming
    Replies: 4
    Last Post: 09-16-2005, 03:58 PM
  3. problems with overloaded '+' again
    By Brain Cell in forum C++ Programming
    Replies: 9
    Last Post: 04-14-2005, 05:13 PM
  4. Linked List Help
    By CJ7Mudrover in forum C Programming
    Replies: 9
    Last Post: 03-10-2004, 10:33 PM
  5. "Operator must be a member function..." (Error)
    By Magos in forum C++ Programming
    Replies: 16
    Last Post: 10-28-2002, 02:54 PM