I am working on some code takes a string as input and returns it reversed.
When I input a string, I get an "abort trap: 6" error. I think the issue is in my use (misuse?) of strcpy, but GDB is not being helpful and other questions on SO about this error and strcpy have not helped me understand why I am getting this error.
I have added some comments to my code explaining the intended functionality.
Thank you for any help or reading material you can provide!
#include <stdio.h>
#include <string.h>
int main()
{
char line[1024];
fgets(line,sizeof(line),stdin);
int size = strlen(line);
for(int I = 0; I <size-I;I++)
{
char temp;
int relative_size = size-I;
strcpy(&temp,&line[I]);//??copies Ith character of line to temp??
strcpy(&line[I],&line[relative_size]); //??swaps characters at [I] and [size-I]??
strcpy(&line[relative_size],&temp);
}
printf("%s", line);
return 0;
}
strcpy()
does not copy a single character, but a whole 0-terminated string. Thereforestrcpy(&temp, &line[i]);
is a "buffer overflow" (temp
isn't really a buffer), ifline[I]
isn't\0
. To copy a single character, simply assign it:This applies to the following two statements, too.