0

I am trying to learn the fundamentals of C, but I cannot figure out why this code doesn't work. The while loop in reverse() causes a bus error. I found almost identical code in a programming interview book as a valid solution, but neither this nor other similar methods I have seen posted here work for me without a bus error.

#include <stdio.h>

void reverse(char* str) {
 char* end = str;
 char tmp = 0;
 if(str) {
  while(*end) {
   end++;
  }
  --end;
  while(end>str) {
   tmp = *end;
   *end-- = *str;
   *str++ = tmp;
  }
 }
}

int main() {
 char* a = "12";
 puts(a);
 reverse(a);
 puts(a);

 return 0;
}
Gilles 'SO- stop being evil'
  • 104,111
  • 38
  • 209
  • 254
Tiki
  • 1,206
  • 1
  • 13
  • 17
  • 1
    See http://stackoverflow.com/questions/4493139/are-string-literals-const and many other questions (like at least once a week) on SO. – ephemient Jan 24 '11 at 19:05

3 Answers3

5

The problem is that you're trying to reverse a constant literal string, which is read only. Change the declaration of a in main to char a[] = "12"; to make it a writable char array instead

Chris Dodd
  • 119,907
  • 13
  • 134
  • 226
2

You are trying to change a string literal which leads to undefined behavior.

Change

char* a = "12";

to

char a[] = "12";
codaddict
  • 445,704
  • 82
  • 492
  • 529
-2

Because end and str point to the same memory location -> they're two different names of the same object. You can avoid using two variables:

char foo[20] = "abcdefghi", tmp;
int counter = 0, length = strlen(foo);

for(counter, counter < length / 2; counter++) {
    tmp = foo[counter];
    foo[counter] = foo[length - counter];
    foo[length - counter] = tmp;
}
BlackBear
  • 22,411
  • 10
  • 48
  • 86
  • "object"? This is C! (Anyway, `end` and `str` only point to the same location for a couple lines of code.) – ladenedge Jan 24 '11 at 19:07
  • That is missing the point of the in situ reverse: Use two pointers that work within the string buffer. Low level stuff, sure; but it should be efficient and fast. – winwaed Jan 24 '11 at 19:08
  • 1
    @ladenedge: "Object" is the correct word as used in the C language standard. – R.. GitHub STOP HELPING ICE Jan 24 '11 at 19:26
  • @R.: well shut my mouth. "object: region of data storage in the execution environment, the contents of which can represent values." Thanks for the correction! – ladenedge Jan 26 '11 at 20:58