tags:

views:

146

answers:

2

I have the simple function below which swap two characters of an array of characters (s). However, I am getting a "Unhandled exception at 0x01151cd7 in Bla.exe: 0xC0000005: Access violation writing location 0x011557a4." error. The two indexes (left and right) are within the limit of the array. What am I doing wrong?

void swap(char* s, int left, int right) {
    char tmp = s[left];
    s[left] = s[right];
    s[right] = tmp;
}

swap("ABC", 0, 1);

I am using VS2010 with unmanaged C/C++. Thanks!

+7  A: 

You can't modify a string literal. instead try this:

char s[] = "ABC"
swap(s, 0, 1);
printf("%s\n", s);
Evan Teran
This is correct. Try using this code to call it: char swapStr[3] = "ABC"; swap(swapStr,0,1)
TerrorAustralis
+1: Beat me to the answer by a few seconds.
Nathan S.
Thank you guys! It works!
Martin
@Dave: careful, your example doesn't have a NUL terminator, the buffer needs to be 4 chars big!
Evan Teran
@Evan Well at least if you want the printf() to work. swap() doesn't mind
Alexandre Jasmin
@GMan: I believe it is legal to have an array which is the size of all the characters in a string literal without the NUL (aka 3 for "ABC"). The character array is simply not NUL terminated (and therefore not really a "string"). But the code is legal so long as you don't operate on it as if it were a NUL terminated string.
Evan Teran
@GMan: which particular version of the standard is that from? My copy of both the C89/C99 standards don't even have a section 8 (7 is the library reference, then come the annexes).
Evan Teran
Ah, found it. C++ **8.5.2/2**. However, I believe that this is a divergence from C89/99 which has no such example.
Evan Teran
@Evan: Oh, I'm an idiot. I completely assumed this question was C++, not C. You're right, of course. I'll delete my other comments. To conclude: `char a[3] = "ABC";` is ill-formed in C++, and well-formed in C (truncating.)
GMan
In addition, the C standard has 6.7.8/32 which uses `char s[] = "abc", t[3] = "abc";` as both legal examples of initializing a character array. and specifically says they are equivalent to: `char s[] = { 'a', 'b', 'c', '\0' },t[] = { 'a', 'b', 'c' };`
Evan Teran
@Gman: no worries, an honest mistake.
Evan Teran
+1  A: 

"ABC" is in the RODATA section, so you can't change it, please see the assembly:

        .section        .rodata
.LC0:
        .string "ABC"
wenlujon