1

I have something like this in my code:

char *objects[] = {"_muldi3.o","_negdi2.o","_lshrdi3.o","_divdi3.o","_moddi3.o","_udivdi3.o"};
/* Around 127 strings stored above, listed only few here. */

char *divmod_objs[]={"_divdi3.o","_moddi3.o","_udivdi3.o"};

for (i=0;i<obj_count;i++) 
{
    if (objects[i]==divmod_objs[0]) 
        break;
    else
    {
        /* do something */
    }
}

The if statement seems to give "Segmentation fault (core dumped)" so I might be doing something wrong. What is the right way to compare these strings?

1
  • Probably obj_count is actually larger than the number of strings in the list Commented Dec 4, 2015 at 11:07

2 Answers 2

1

Segmentation fault basically means a pointer accessed memory outside of it's bounds (it's allocated memory area).

There is a core mistake in your code, in which you expect the equality operator "==" to compare strings the way it works in Java or C#. But the comparison of strings does not work like that in C. Instead what happens is that you it is trying to compare the [0..(obj_count-1)] char elements of the first string pointed to by "objects" array pointer to the first character of the first string pointed to by the "divmod_objs" pointer. Since the strings in object could end up being > obj_count, in that case a seg. fault is thrown up.

If you want to implement string comparison in C, you need to implement a comparison on character-by-character basis.

Basically You would need a double loop, the outer one would iterate through the string objects, the inner one would iterate within the characters of the individual strings. Plus some bells and whistles to check for array bounds etc.

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks a lot Mr.Jas, I realised my blunder! :)
0

Write simple function to compare strings:

bool equal(char a[], char b[])
{
    for (int i = 0; a[i] != '0' && b[i] != '0'; i++) {
        if (a[i] != b[i]) return false;   
    }
    return true;
}

and use it in your code:

char *objects[] = {"_muldi3.o","_negdi2.o","_lshrdi3.o","_divdi3.o","_moddi3.o","_udivdi3.o"};
/* Around 127 strings stored above, listed only few here. */

char *divmod_objs[]={"_divdi3.o","_moddi3.o","_udivdi3.o"};

for (i=0;i<obj_count;i++) 
{
    if (equal(objects[i], divmod_objs[0])) 
        break;
    else
    {
        /* do something */
    }
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.