Why is this string reversal C code causing a segmentation fault? [duplicate]

There’s no way to say from just that code. Most likely, you are passing in a pointer that points to invalid memory, non-modifiable memory or some other kind of memory that just can’t be processed the way you process it here.

How do you call your function?

Added: You are passing in a pointer to a string literal. String literals are non-modifiable. You can’t reverse a string literal.

Pass in a pointer to a modifiable string instead

char s[] = "teststring";
reverse(s); 

This has been explained to death here already. "teststring" is a string literal. The string literal itself is a non-modifiable object. In practice compilers might (and will) put it in read-only memory. When you initialize a pointer like that

char *s = "teststring";

the pointer points directly at the beginning of the string literal. Any attempts to modify what s is pointing to are deemed to fail in general case. You can read it, but you can’t write into it. For this reason it is highly recommended to point to string literals with pointer-to-const variables only

const char *s = "teststring";

But when you declare your s as

char s[] = "teststring";

you get a completely independent array s located in ordinary modifiable memory, which is just initialized with string literal. This means that that independent modifiable array s will get its initial value copied from the string literal. After that your s array and the string literal continue to exist as completely independent objects. The literal is still non-modifiable, while your s array is modifiable.

Basically, the latter declaration is functionally equivalent to

char s[11];
strcpy(s, "teststring");

Leave a Comment

tech