Your statement:
strncpy(somefile,argv[0],sizeof(argv));
is handing the length of a pointer (i.e likely 4 or 8) to the 3rd argument instead of the actual size of the string. Change it to:
char somefile[strlen(argv[0])+1]; // note extra space for NULL terminator...
strncpy(somefile,argv[0],strlen(argv[0])+1); // ...here as well
Note, strncpy(dest, src, n)
(for example) copies at most n
characters of the character array pointed to by src. If n
is reached before the entire array src
was copied, the resulting character array, dest
is not null-terminated. To mitigate this potential, you may consider doing the following:
char src[] = "this string is too long";
char dest[10];
int n = 10;
strncpy (dest, src, n);
results in dest
containing:
|t|h|i|s| |s|t|r|i|n|?|?|?|...// may, or may not have a null terminator somewhere.
dest[n-1] = 0;
results in dest
containing:
|t|h|i|s| |s|t|r|i|\0|?|?|?|...// guaranteed NULL termination.
And since somefile
was created so specifically based on argv[0]
strcpy(somefile,argv[0]);
would do just as well in this situation.