Skip to content

What is going on in this simple C code?

An answer to this question on Stack Overflow.

Question

I am in the process of teaching myself C. I have the following code that prints a string char by char forwards and backwards:

#include<stdio.h>
#include<string.h>
main(){
	char *str; 
	fgets(str, 100, stdin);
	//printf("%i", strlen(str));
	int i;
	
	for(i = 0; i < strlen(str) - 1; i++){
		printf("%c", str[i]);
	}
	for(i = strlen(str); i > -1; i--){
		printf("%c", str[i]);
	}
}

When run, it gives me the following output (assuming I typed "hello"):

cello
ollec

In addition, if I uncomment the 7th line of code, I get the following output (assuming I typed "hello"):

6 

For the life of me, I cannot figure out what I am doing that is causing the first character in the output to change. In the second example, I know that the string length would be 6 because 'h' + 'e' + 'l' + 'l' + 'o' + '\0' = 6. That is fine, but where is the spade symbol coming from? Why is it only printing one of them?

It is pretty obvious to me that I have some kind of fundamental misunderstanding of what is happening under the hood here and I cant find any examples of this elsewhere. Can anyone explain what is going wrong here?

Answer

You should preallocate space for your string, otherwise you are writing to who knows where, which is bad.

char str[100]; //I must be big enough to hold anything fgets might pass me

You should also be sure to only access parts of the string which contain characters:

for(i = strlen(str)-1; i > -1; i--){
    printf("%c", str[i]);
}

Note that the character at strlen(str) is \0, the string-terminating null character. So you can access this space, but trying to print it or otherwise treating it like a standard letter is going to lead to issues at some point.