Monday, 15 June 2015

C Programming - Segmentation fault when Manipulating Array of Strings -


I am struggling with a partition fault that occurs when the DNS variable changes from size to size 10 goes. I believe the announcement is mainly making an array of DNS 10 stars in the DNS, and then when there is an array of 32 strings to increase from 32.

So when the 10-shaped DNS variable is executed, I get the output of 4 directories. The name starts with the name D. This is expected output.

If I increase the DNS variable in 32, then I still get 4 directory names and there is a segmentation mistake immediately after that.

It has been very long since coding and I am sure that I am violating memory somewhere

Any help is greatly appreciated.

Thanks,

Donations.

  void ld_dirs (char * string []) {Int count; DIR * DP; Struct dirent * ep; DP = opendir ("/ tmp / sysinfo / inputs"); If (dp! = Null) {count = 0; While (ep = readdir (dp)) {if (ep-> d_name [0] == 'D') {strings [count] = malloc (80 * sizeof (char)); Wire [count] = EP- & gt; D_name; Count ++; }} Monkey (DP); } And lies ("could not open the directory"); } Int main () {four cwd [120]; Integer number, count 2; Four * DNS [10]; Four * paths; If (getcwd (cwd, sizeof (cwd)) = NULL printf ("\ n current work directory:% s \ n \ n \ n", cwd); Other error ("getcwd () error"); Ld_dirs (DNS); Calculation = 0; ("List of valid inputs: \ n"); While (DNS [count]! = Null) {puts (DNS [calculation]); Count ++; } Printf ("% d valid input \ n", counting); Return 0;  

The problems I have:

  1. Size of the array

    You have declared:

      four * DNS [10];  

    You do not have any code in ld_dirs to make sure that you can not use string , which Can hold it legally.

  2. You have not initialized items from dirs to NULL , yet you are relying on the value of the items In the NULL the following while the loop.

      while (DNS [count]! = Null] {puts (dns [count]); Count ++; }  
  3. You can fix these problems by:

    1. DNS Ho NULL .

        char * dns [10] = {0};    
    2. Pass the size of the array with ld_dir and make sure that you legally agree that you do not use any more Are there.

      Change the function interface to:

        zero ld_dirs (four * strings [], integer size)  

        ld_dirs (DNS, size (DNS) / size (* DNS);  

1 comment: