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:

  1. char*test=file , strcpy(list[list_size],test). segmentation fault.

  2. char*test=malloc(sizeof(char)*max_filename_len+1) , test=file andstrcpy(list[list_size],test). segmentation fault.

  3. 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.

  1. 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.

  2. you allocate memory , point @ test. forget memory when let test point @ file instead, have created memory leak. , once have done that, same bug in 1, since variables test , file have nothing list.

  3. same bug in 1 , 2.

i advise studying pointers , arrays bit more before diving dynamic memory allocation , string handling.


Comments

Popular posts from this blog

c# - DetailsView in ASP.Net - How to add another column on the side/add a control in each row? -

javascript - firefox memory leak -

Trying to import CSV file to a SQL Server database using asp.net and c# - can't find what I'm missing -