I’m trying to do a couple simple implementations of string_reverse in C. However, I get the following error when I debug in 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
Here’s my code for the error I’m getting (I commented on the line where the error comes from):
#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;
}
I know that strlen returns the length of a passed string by advancing through the string until it lands on \0, the null byte. So I’m wondering if perhaps the string passed is somehow not null-terminated? I don’t think I declared the strings incorrectly in main though.
Thanks for any insight.
The problem is when you call
string_reverse1:The
*beforechar1dereferenceschar1returning the value of the first character of the string. If you want to pass the*charyou should just omit the*. This is because the type ofchar1is alreadychar *. There’s no need to change it.When you dereference
char1you’re sending the actual ascii value of the first character, ‘h’. Thenstrlenis attempting to access the memory at address ‘h’ and segfaulting because that’s just some arbitrary memory location.