3

Possible Duplicate:
What is the difference between char s[] and char *s in C?
Why does this program give segmentation fault?

here is the code:

#include <stdlib.h>
#include <stdio.h>
#include <string.h>

void reverse(char *c){
    int len = strlen(c);
    char tmp;
    int i;
    for(i = 0; i < len; i++){
        tmp = c[len-1-i];
        c[len-1-i] = c[i];
        c[i] = tmp;
    }
}

int main(){
    char *s = "antonio";
    //printf("%zd\n", strlen(s));
    reverse(s);
    printf("%s\n", s);
    return 0;
}

The issue is in reverse(char *c), it take a string ad reverse it, but I don't understand where it goes wrong.

Community
  • 1
  • 1
AR89
  • 3,548
  • 7
  • 31
  • 46
  • 2
    You're trying to modify a string literal. That's undefined behaviour and usually crashes. – Daniel Fischer Nov 18 '12 at 16:39
  • 2
    You've failed to use your compiler warnings and/or pay attention to them. Compile the code again with all warnings enabled and make sure you understand everything the compiler tells you. Automated tools can get you a very long way before you need to come to SO for help! – Kerrek SB Nov 18 '12 at 16:39
  • @KerrekSB I didn't receive any warning, I will see how to enable all the warnings of my compiler. – AR89 Nov 18 '12 at 17:14

1 Answers1

6

There are two bugs here:

1)

You are trying to change a string literal, which leads to undefined behavior, manifested as bus error in your case.

Change

char *s = "antonio";

to

char s[] = "antonio";

2)

Also you are running your loop counter for entire string length:

for(i = 0; i < len; i++)

this way you'll get back the original string. What you want is to swap only half of the characters with other half:

for(i = 0; i < len/2; i++)
codaddict
  • 445,704
  • 82
  • 492
  • 529
  • possible duplicate of http://stackoverflow.com/a/3735133/635608 – Mat Nov 18 '12 at 16:40
  • @codaddict what is the difference between: char *s = "antonio"; char s[] = "antonio"; char s* = malloc(size);? I know that function(char a[]) became function(char *a), what happen in this case? – AR89 Nov 18 '12 at 17:12