具有结构和功能的分段错误

时间:2014-05-09 02:14:08

标签: c struct segmentation-fault function-pointers


我在查找和解决可怕的分段错误问题时遇到了一些困难。我创建了一个带有数组的“struct”,并用随机字符填充。从那里我计算水平和垂直对。在运行 function3()之前,一切似乎都很好。从那里出现了分段错误。我运行GDB来查找错误,但我不知道为什么它不起作用,因为我已经为 function2()做了类似的功能,并且可以使用该功能。我不确定我是否错过了指针。我已经玩过添加和减去指针而没有运气。

#include <stdio.h>
#include <stdlib.h>
#include <time.h>

#define ROW 12
#define COL 15

typedef struct letter_array {
    char** letters;
    struct letter_array *ltr_ptr;
} larray;

void function1 (larray * letter1);
int function2 (larray  * letter2);
int function3 (larray * letter3);
void function4 (int hor_ans, int ver_ans);

int  main ( void )
{  

larray letter_list;
int vert, hori, count;

letter_list.letters = malloc(ROW*sizeof(int*));
for(count = 0; count<ROW; count++)
    {
    letter_list.letters [count] = malloc(COL*sizeof(int));
    }

printf("\n \t\t\t *** Hello! ***");

printf("\n This program will create a random selection of 180 upper-case"
    " characters. \n\n");

function1(&letter_list);

hori = function2(&letter_list);

vert = function3(&letter_list);  //The Problem?

free(letter_list.letters);

return ( 0 ) ;
}    


void function1 (larray *letter1)  // Assign random letters to array.
{
int i, z;

    srandom((unsigned)time(NULL));

for(i=0; i<ROW; i++)
 { 
    for(z=0; z<COL; z++)
    {
    letter1->letters[i][z] = random( )%26+'A';
    printf("%c ", letter1->letters[i][z]);
    }
 printf("\n");
 }

return ;
}

int function2 (larray * letter2)  //Count horizontal pairs.
{
int a,b;
int m=0;
    for(a=0; a<ROW; a++)
    {
       for(b=0; b<COL; b++)
       {
        if (letter2->letters[a][b] == (letter2->letters[a][b+1]))
        m++;
       }
    }

 return (m);
 }


 int function3 (larray * letter3)  //Count vertical pairs.
 {
 int a,b;
 int n=0;
    for (a=0; a<ROW; a++)
    {
       for(b=0; b<COL; b++)
       {
        if (letter3->letters[a][b] == (letter3->letters[a+1][b])) //THE Problem..?
        n++;
       }
    }
return (n);

在GDB ......

Program received signal SIGSEGV, Segmentation fault.
0x0000000000400ad8 in function3 (letter3=0x7fffffffd8a0)
xxx                 if (letter3->letters[a][b] == (letter3->letters[a+1][b]))
(gdb) backtrace
#0  0x0000000000400ad8 in function3 (letter3=0x7fffffffd8a0) 
#1  0x000000000040088f in main () 
(gdb) up
#1  0x000000000040088f in main () 
xxx      vert = function3(&letter_list);

感谢您的帮助!

1 个答案:

答案 0 :(得分:4)

很明显。 GDB告诉您确切的位置。在你的function3

for (a=0; a<ROW; a++)

然后您尝试访问

letter3->letters[a+1][b]

这里,a+1会导致分段错误(你跑掉阵列的边缘)。