I'm writing code to reverse the char array in every single line I input. However, when I debugged the program, I encountered a segmentation fault and I don't know why. Here is my code:
#include <stdio.h>
#define DEFAULT 1000
int reverse(char s[]);
main()
{
int i;
char line[DEFAULT] = {'\0'};
while ((i = getline(line, DEFAULT)) != 0) {
printf("%s", reverse(line));
}
return 0;
}
/*reverse a line*/
int reverse(char s[])
{
int i = 0, j = 0;
while (s[i] != '\n')
++i;
for (j = 0; j < i; ++j) {
s[2 * i - j] = s[j];
}
for (j = 0; j < i; ++j) {
s[j] = s[j + i + 1];
s[j + i + 1] = '\0';
}
return i;
}
/*get a line from input stream*/
int getline(char s[], int lim)
{
int i, c, j = 0;
for (i = 0; ((c = getchar()) != EOF) && (c != '\n'); ++i) {
if (i < lim - 2) {
s[j] = c; // use j to prevent index out of bounds
++j;
}
}
if (c == '\n') {
s[j] = c;
++j;
}
s[j] = '\0';
return i; // return the length of char s[]
}
When I input "abc\n" and execute reverse(s), the content in s becomes "cba\n" and i refers to 3, everything is okay. The segmentation fault happens when I step out of that function.
Here are some more details:
Complier: GCC 4.9.2 64-bit Release
System: Windows 10
Your function int reverse(char s[])
is returning an int
, and then you're trying to print that resulting int
as a string:
printf("%s", reverse(line));
If you want to use the function like that, you could change its signature to return a char*
instead:
char* reverse(char s[]);
And then return the s
that you're giving in as a parameter. Your compiler should issue a warning about giving the wrong type of parameter to printf
. If not, try to set it to be more strict with warnings.