#include <stdio.h>
#include <string.h>
main()
{
char tmpChar;
char *str_1 = "Hello";
开发者_StackOverflow中文版int index;
int len = strlen(str_1);
for (int i = 0; i < len/2; i++)
{
index = len - 1- i;
tmpChar = str_1[len - i -1];
str_1[index] = str_1[i]; <<<<<--------------- core dumps at this point. Not sure why
str_1[i] = tmpChar;
printf("str_1[%d] = %c\n", i, str_1[i]);
}
str_1[len] = '\0';
printf("str_1 = %s\n", str_1);
}
You are trying to modify the content of a string literal which invokes Undefined Behaviour. String literals are generally stored in read only section of memory and have static storage duration.
char *str_1 = "Hello";
. In this case "Hello"
is a string literal(stored in read only section) and you are trying to modify the content by doing this
str_1[index] = str_1[i];
Instead of making str_1
a pointer to the literal [i.e. char *str_1 = "Hello"
] make it an array of characters i.e. char str_1[] = "Hello"
. The content of the literal would be copied onto the stack and you won't get any segfault if you try to modify the content then.
Change
char *str_1 = "Hello"; //read only
as
char str_1[] = "Hello";
The ISO C99 standard has this to say about string literals (section 6.4.5/6):
It is unspecified whether these arrays are distinct provided their elements have the appropriate values. If the program attempts to modify such an array, the behavior is undefined.
That's because, typically, all the string literals are lumped into a single area which may be marked read-only, and they're sometimes merged to save space. In other words, the two string literals:
char *p1 = "Googolplex";
char *p2 = "plex";
may be stored thus:
+--- p1 p2 ---+
| |
V V
+---+---+---+---+---+---+---+---+---+---+----+
| G | o | o | g | o | l | p | l | e | x | \0 |
+---+---+---+---+---+---+---+---+---+---+----+
That means: don't try to modify them. It may work under certain situations but it's not something that you should rely on if you value portability even a little.
Change:
char *str_1 = "Hello";
to:
char str_1[] = "Hello";
since this is effectively the same as:
char str_1[6];
strcpy (str_1, "Hello");
精彩评论