sharewind
sharewind

Reputation: 2419

Why did I get EXC_BAD_ACCESS?

I want to reverse a string, but I got a error on swap char.

Could someone help me with this?

char*  reverse_char(char* src){
    char *p,*q;
    p = q = src;
    while(*(p) != '\0'){
        p++;
    }
    p--;

    char  temp = '\0';
    while (p > q) {
        temp = *p;
        *p = *q; // I got exec bad access here ??? why 
        *q = temp;
        p--;
        q++;
    }
    return src;
}

This is the main method.

int main(int argc, char const* argv[])
{
    char *hi = "hello world!\n";
    printf("%s", hi);

    reverse_char(hi);
    printf("%s", hi);
    return 0;
}

Upvotes: 0

Views: 2436

Answers (2)

Vlad from Moscow
Vlad from Moscow

Reputation: 310920

Though string literals in C have types of non-const character arrays they may not be changed.

From the C Standard (6.4.5 String literals)

7 It is unspecified whether these arrays are distinct provided their elements have the appropriate values. If the program attempts to modify such an array, the behavior is undefined.

it is better to declare a pointer initialized with a string literal as having type const char * as it is done in C++. For example

const char *hi = "hello world!\n";

In this case instead of a run-time error you would get a compile-time error that would be understandable because the parameter of the function is declared as a non-const character pointer.

You have to use a character array instead of a pointer to a string literal.

For example

char hi[] = "hello world!\n";

As for the function that it has some problem when a pointer points to an empty string. In this case after operation

p--;

you can get invalid pointer that is not necessary less than src.

I would write the function the following way

char*  reverse_string( char *s )
{
    char *p = s;

    while ( *p ) ++p;

    if ( p != s )
    {
        for ( char *q = s; q < --p; ++q )
        {
            char c = *q;
            *q = *p;
            *p = c;
        }
    }

    return s;
}

Upvotes: 2

Mohit Jain
Mohit Jain

Reputation: 30489

Replace char *hi = "hello world!\n"; with char hi[] = "hello world!\n";

"hello world!\n" is string literal and may not be writable causing the access error. Modifying the contents of string literal is undefined behavior, it may write the contents silently, raise an access error or may do something else unexpected. (So you should not write to string literal)

Summing up

char a[] = "...";  /* Contents of a can be assigned */
char *a = "...";   /* Writing to contents of memory pointed by a leads to UB */

Upvotes: 6

Related Questions