terminology - C programming , need help understanding some concept -
this simple program have done in c , works fine don't understand terminology:
instead of list[list_size] = strdup(file)
do:
char*test=file
,strcpy(list[list_size],test)
. segmentation fault.char*test=malloc(sizeof(char)*max_filename_len+1)
,test=file
andstrcpy(list[list_size],test)
. segmentation fault.or
strcpy(list[list_size],file)
. segmentation fault.# include < stdio.h > # include < string.h > # define max_list_size 1000 # define max_filename_len 128 int main() { file * infile; char * list[max_list_size], file[max_filename_len + 1]; size_t list_size = 0; infile = popen("ls", "r"); if (infile != null) { while ((list_size < max_list_size) &&(fscanf(infile, "%s", file) == 1)) { list[list_size] = strdup(file); list_size++; puts(file); } } pclose(infile); return 0;
}
it great if help.
the non-standard strdup function 2 things: allocates dynamic memory , copies string. same thing calling malloc followed call strcpy (which why strdup 100% superfluous function).
when
strcpy(list[list_size],test)
, list isn't pointing @ allocated memory - pointing @ random memory location anywhere in memory. try copy data random location , crash.you allocate memory , point @
test
. forget memory when lettest
point @file
instead, have created memory leak. , once have done that, same bug in 1, since variablestest
,file
have nothinglist
.same bug in 1 , 2.
i advise studying pointers , arrays bit more before diving dynamic memory allocation , string handling.
Comments
Post a Comment