user1089679
user1089679

Reputation: 2368

Getting Segmentation Fault in String Manipulation

Here i give input string like this "/org/bluez/1509/hci0"

And i want output like this /org/bluez/1509/hci0

Here i use this method but i got Segmentation fault.

void main () 
{
    char  *str = "\"/org/bluez/1509/hci0\"";
    int len = strlen(str);
    printf("\nlength %d\n",len);
   char *str1;
   str1 = str+1;
   printf("String 1 = %s\n",str1);
   *(str1+ (strlen(str)-2)) = '\0'; 
   printf("\nString 1 = %s\n",str1);
}

I am getting output like this

length 22
String 1 = /org/bluez/1509/hci0"
Segmentation fault

Problem with Last " character.

Can Any body Help me or Suggest me new Way.?

Upvotes: 0

Views: 215

Answers (1)

sidyll
sidyll

Reputation: 59297

Use

char str[] = "\"/org/bluez/1509/hci0\"";

Instead of a pointer. The pointer only "points" to the string literal which is not modifiable. You can read more about this in this question and a ton of other similar ones. It's even in the c-faq, take a look on it!

Upvotes: 4

Related Questions