Hello
I am reminding myself of C after many years. I have found a very strange
run time error, "Segmentation Fault", I don't remember ever seeing this.
There are no compiler errors! What is wrong with my code??
Almost everything. To begin with, you're missing headers
for the library functions you call:
#include <stdio.h>
#include <stdlib.h>
#include said:
main(char * argv [], int argc)
Next problem: The parameters are backwards. It doesn't
matter what you name them, but the `int' must be first and
the `char**' second.
{
char NAME[1024 * sizeof (char)] = {0}; // declare static array
Next problem: This isn't a static array. (Not really a
"problem," in the sense that you don't actually need a static
array -- but if you think you're getting one, you're wrong.)
Next problem: There's no reason to initialize the array
to zeroes. It doesn't hurt anything, but it also doesn't help:
You're going to overwrite the array anyhow -- all of it that
you care about, at any rate.
Next problem: // is a syntax error in C90. It starts a
comment in C99, but we know you're not using a C99 compiler
(because such a compiler would have complained loudly about
the type-less definition of main() and about all the calls
to undeclared library functions.)
// build up the output buffer
Same problem again: // is a syntax error.
if ( strlen (argv[1])> 1000 ) {
Next problem: Even if you swap the parameters into the
right order, you don't know whether argv[1] exists unless you
first look at argc or at argv[0]. Even if argv[1] exists, it
might be a null pointer.
printf("Buffer overflow error please restart");
Next problem: No \n character to end the line.
abort();
}
strcpy(NAME, "Hello ");
strcat(NAME, argv[1]);
strcat(NAME, " have a nice day");
// display the buffer
printf(NAME);
Next problem: If argv[1] is something like "%solution"
this printf() call will go off the rails.
Next problem: Another absent \n.
Next problem: You fall off the end of int-valued main()
without returning a value. In C99 there's a special dispensation
that makes this equivalent to returning zero, but we know you're
not using C99.
Final problem: All this strlen()-ing and strcat()-ing
is just plain silly. Once you've determined argv[1] exists
printf ("Hello %s have a nice day\n", argv[1]);
does the trick, safely, sleekly, and without all that foolish
mucking about.