Upon compiling and running this small program to reverse a string, I get a Segmentation Fault before any output occurs. Forgive me if this is an obvious question, I’m still very new to C.
#include <stdio.h>
int reverse(char string[], int length);
int main() {
char string[] = "reversed";
printf("String at start of main = %s", string);
reverse(string, sizeof(string));
printf("%s\n", string);
return 0;
}
// Reverse string
int reverse(char string[], int length) {
int i;
char reversed[] = {};
int temp;
for(i = 0; i < length; ++i) {
temp = string[i];
reversed[length - i] = temp;
}
return 0;
}
Because of this:
First you create an array with zero elements:
And later you attempt to write to that array beyond its bounds:
Update:
The above means that you need to allocate memory whose size is only known at runtime (it’s
length). The usual C-style way of doing this is… by pushing the burden of memory allocation to your caller:This function would write to a buffer provided by the caller, who now also must ensure that: