1

The problem I want to solve is: Count the number of occurrences of key words in a C code. Here's the code:

The problem is that I get a segmentation fault. In my code I mentioned where is the problem. Can you, please, explain me why ?

In header:

struct Chei
{
    char *cuv;
    int contor;
};

typedef struct Chei chei;

int ReadCode(char *a[]);
void  determine(chei *Ch, char *temp, int size);
void Frequency(chei *Ch, int nr_lines, char *a[], int size);

In main:

    chei tab_chei[] = {{"while", 0},{"if", 0}, {"case", 0}, {"switch",  0}};
    int size = sizeof(tab_chei)/sizeof(tab_chei[0]);
    char *Code[MaxL];
    int nr_lines;


    nr_lines = ReadCode(Code);//number of lines of text

    Frequency(tab_chei, nr_lines, Code, size);

In function file: I think there is no problem with reading text (function ReadCode() -- here I allocated memory for each Code[i] using malloc). I used an array of pointers to char for this.

// This functions determines if the word "temp" is a keyword, and increases
     //"contor" if it is.

void  determine(chei *Ch, char *temp, int size)
{
    int i;


    for (i = 0; i < size; ++i)
    {
        if (!strcmp(Ch[i].cuv, temp))
        {
            Ch[i].contor++;
            break;
        }
    }
}

Array "a" contains the text.

void Frequency(chei *Ch, int nr_lines, char *a[], int size)
{
    int i;
    char temp[MaxCh];
    char *token = 0;


        strcpy(temp, a[0]);//I put a[0] as a particular case
        token = strtok(temp, " ");
        determine(Ch, token, size);

        while (token != NULL)
        {

            token = strtok(NULL, " ");
            determine(ch, token, size); //here is the problem.
//I observed that if I delete this line, there is no error
//but still it isn't what I want to get
        }

        for (i = 0; i < size; ++i)
            {
                printf("\n%-10s%-4d", Ch[i].cuv, Ch[i].contor);
            }

}
wonderingdev
  • 1,132
  • 15
  • 28

2 Answers2

1

I think the problem is that you did not allocate memory for each of the string the pointer will point to, char *Code[MaxL];.

you only allocated memory for the pointers, you need to do something like

Code[0] = calloc(0, 100);

.

CS Pei
  • 10,869
  • 1
  • 27
  • 46
  • 2
    Don't cast malloc/calloc results in C: http://stackoverflow.com/questions/605845/do-i-cast-the-result-of-malloc – rost0031 May 13 '15 at 19:23
  • o, I did not know that the ReadCode() allocate memory for it. And thanks, Rost0031. – CS Pei May 13 '15 at 19:25
1
token = strtok(NULL, " ");
determine(ch, token, size); //here is the problem.

You're not checking token before passing it to determine(). The strcmp() call is undefined behaviour when given a null pointer.

isanae
  • 3,253
  • 1
  • 22
  • 47