I have defined a function that returns a pointer to a reversed copy of the main's argv
argument. When I print the results with the string formatter %s\n
the effect is strange:
#include <stdio.h>
/* Returns a pointer to a reversed copy of argv */
char **revargv(int n, char *argv[])
{
char *cpy[n];
char **cpyptr = cpy;
for (int i = 0; i < n; i++)
cpy[i] = argv[n-1-i];
return cpyptr;
}
int main(int argc, char *argv[])
{
char **argvr = revargv(argc-1, ++argv);
for (int i = 1; i < argc; i++)
printf("%s\n", *argvr++);
return 0;
}
Now I call it from the terminal after compilation ./rev emacs lisp ruby perl python
and the output is
python
Segmentation fault
If I add at least one character to the beginning of printf's formatter like
int main(int argc, char *argv[])
{
char **argvr = revargv(argc-1, ++argv);
for (int i = 1; i < argc; i++)
printf(" %s\n", *argvr++);
return 0;
the output is as I expect:
python
perl
ruby
lisp
emacs
Can anyone help me understand why is this happening?
Update
Would it be a correct approaech to allocate memory in the function and free it up after the function call like this:
char **revargv(int n, char *argv[])
{
char **mem = malloc(n); /* Global memory access */
char **mem_p = mem;
for (int i = 0; i < n; i++) {
*mem = argv[n-1-i];
mem++;
}
return mem_p;
}
int main(int argc, char *argv[])
{
char **argvr = revargv(argc-1, ++argv);
char **argvr_p = argvr;
for (int i = 1; i < argc; i++) {
printf("%s\n", *argvr++);
}
free(argvr_p);
return 0;
}