我正在尝试在 C 中执行几个简单的 string_reverse 实现。但是,当我在 gdb 中调试时出现以下错误:
Program received signal SIGSEGV, Segmentation fault.
0x00000000004005ca in string_reverse1 (string=0x68 <Address 0x68 out of bounds>)
28 length = strlen(*string);
Missing separate debuginfos, use: debuginfo-install glibc-2.15-58.fc17.x86_64
这是我遇到的错误的代码(我评论了错误的来源):
#include <stdio.h>
#include <string.h>
int main(int argc, char *argv[])
{
char *char1 = "hello";
char *char2 = "hi";
char *char3 = "this is a really long string!";
string_reverse1(*char1);
string_reverse1(*char2);
string_reverse1(*char3);
printf("%s, %s, %s\n", char1, char2, char3);
return 0;
}
//Assuming method's purpose is to reverse the passed string
//and set the original string equal to the reversed one
void string_reverse1(char *string)
{
//Calculate length once so it isn't recalculated at
//every iteration of the for loop
int length;
char *reversed;
int i;
int reversed_counter;
length = strlen(*string); //ERROR
reversed_counter = 0;
for(i = length - 1; i >= 0; i--) {
reversed[reversed_counter] = string[i];
reversed_counter++;
}
//Can't forget to add the terminating null character!
reversed[length] = '\0';
string = reversed;
}
我知道 strlen 通过推进字符串返回传递字符串的长度,直到它到达 \0,即空字节。所以我想知道传递的字符串是否以某种方式不是以空值结尾的?我不认为我在 main 中错误地声明了字符串。
感谢您的任何见解。