This is a very simple program I have done in C and works fine but I don't understand some terminology:

Instead of list[list_size] = strdup(file) I do:

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

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

  3. Or even strcpy(list[list_size],file). I get 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 would be great if someone could help.

有帮助吗?

解决方案

  1. The non-standard strdup function does two things: it allocates dynamic memory and it copies the string. It is the very same thing as calling malloc followed by a call to strcpy (which is why strdup is a 100% superfluous function).

    When you do strcpy(list[list_size],test), list isn't pointing at any allocated memory - it is pointing at a random memory location anywhere in the memory. You try to copy data into this random location and get a crash.

  2. You allocate memory and point at it with test. Then you forget all about that memory when you let test point at file instead, you have created a memory leak. And once you have done that, you do the very same bug as in 1, since the variables test and file have nothing to do with list.

  3. Same bug as in 1 and 2.

I would advise studying pointers and arrays a bit more before diving into dynamic memory allocation and string handling.

其他提示

char *list[MAX_LIST_SIZE];

Here, the elements of list are uninitialized, they don't point to valid memory, hence your program invokes undefined behavior. strcpy() returns a pointer that's either NULL or points to some malloc()ated memory, which is, consequentially, valid.

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top