I'm trying to write my own version of strcat (I call it "append"). Here's what I have:
#include <stdio.h>
int main() {
char *start = "start";
char *add = "add";
append(start, add);
printf(start);
}
void append(char *start, char *add) {
//get to end of start word
char *temp = &start;
while (*temp != '\0') {
temp++;
}
*temp = *add;
while (*temp != '\0') {
*temp = *add;
}
}
When I compile, I get 3 warnings and an error:
1) warning: implicit declaration of function 'append' is invalid in C99
2) warning: format string is not a string literal (potentially insecure)
3) error: conflicting types for 'append'
I don't see how the arguments I pass into my append function within main conflict with the function definition below it.
4) warning: incompatible pointer types initializing 'char *' with an expression of type 'char **'; remove &
Why would I want to remove &
here? I thought I could declare and initialize my char
pointer to the proper memory address all at once.
Any help is much appreciated.
You have multiple problems with that short code. First you have
warning: implicit declaration of function 'append' is invalid in C99
The meaning of this warning is that you need to declare functions before you use them. If you don't declare a function before you use it, the compiler will have to guess its arguments and return type, and often it guesses badly.
Continuing with next warning:
warning: format string is not a string literal (potentially insecure)
This is because you provide a string variable to printf
, this is, like the warning tells you, insecure. Think for example about a case where you read input from a user, and use that input as a format string to printf
. What would stop the user from adding format codes in the input string? And since you don't pass arguments where would the arguments for those formats come from?
And now the error:
error: conflicting types for 'append'
This is because of the first problem, that the compiler guessed the arguments or return type of the function wrongly.
Now on to another major problem that doesn't show up as compiler errors or warnings, namely undefined behavior.
The problem is that your start
and add
variables points to string literals. String literal are read only (in fact, a string literal is a pointer to an array of non-modifiable characters). The first problem is that you try to modify the contents of these arrays, the second is that the arrays are only as big as needed and you are writing outside of that memory. Both these problems are causes for undefined behavior.