I have two c program "main.c" and "ArgHandle.c".
main.c
#include <stdio.h>
#include <stdlib.h>
main ( int argc, char * argv[] ){
char * a[4];
save_arg( argc, argv );
a[0]=get_arg(); //warning: assignment makes pointer from integer without a cast
if ( a[0] != NULL )
printf("a[0]=%s\n", a[0] );
}
ArgHandle.c
#include <stdio.h>
#include <stdlib.h>
static char * arg[5];
void save_arg( int argc, char * argv[] ){
int i;
for ( i=1; i<argc; i++ ){
arg[i-1]=argv[i];
printf("save_arg: arg[%d]=%s\n", (i-1), arg[i-1]);
}
}
char * get_arg(){
printf("get_arg: arg[0]=%s\n", arg[0] );
return (arg[0]);
}
And while I execute the program "./main -abc", it returns
save_arg: arg[0]=-abc
get_arg: arg[0]=-abc
Segmentation fault (core dumped)
It can print out the char* argument inside ArgHandle.c but not in main.c after returning from function get_arg().
I am new in c programming and have no idea why would this happens. Then I find Iharob Al Asimi's post, and think maybe I should use malloc()
to reserve non-local memory for the argument. So I revise the code like this:
main.c (revised)
#include <stdio.h>
#include <stdlib.h>
main ( int argc, char * argv[] ){
char * a[4];
save_arg( argc, argv );
a[0]=malloc(50); // <~~~~ new added
a[0]=get_arg(); //warning: assignment makes pointer from integer without a cast
if ( a[0] != NULL )
printf("a[0]=%s\n", a[0] );
free(a[0]); // <~~~~ new added
}
ArgHandle.c (revised)
#include <stdio.h>
#include <stdlib.h>
static char * arg[5];
void save_arg( int argc, char * argv[] ){
int i;
for ( i=1; i<argc; i++ ){
arg[i-1]=malloc(50); // <~~~~ new added
arg[i-1]=argv[i];
printf("save_arg: arg[%d]=%s\n", (i-1), arg[i-1]);
}
}
char * get_arg(){
printf("get_arg: arg[0]=%s\n", arg[0] );
return (arg[0]);
}
But, it makes no difference, the Segmentation fault still comes out.
Solved
Thanks for the suggestion from chux, Retired Ninja and Lưu Vĩnh Phúc. Problem solved by adding the declaration header.