bus error 10 in a c program

c, string

Solution

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++)

Problem

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.

Original source

Related problems