Reputation: 1
Hi please help me with this
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int classmatesize=0;
char **classmate1;
char **classmate2;
void checkclassmates(){
int i,j;
for(i=0;i<classmatesize;i++){
for(j=i+1;j<classmatesize;j++){
if(strcmp(classmate1[i],classmate1[j])==0){
strcpy(classmate1[classmatesize],classmate2[i]);
strcpy(classmate2[classmatesize],classmate2[j]);
classmatesize++;
}else if(strcmp(classmate1[i],classmate2[j])==0){
strcpy(classmate1[classmatesize],classmate2[i]);
strcpy(classmate2[classmatesize],classmate1[j]);
classmatesize++;
}else if(strcmp(classmate2[i],classmate2[j])==0){
strcpy(classmate1[classmatesize],classmate1[i]);
strcpy(classmate2[classmatesize],classmate1[j]);
classmatesize++;
}else if(strcmp(classmate2[i],classmate1[j])==0){
strcpy(classmate1[classmatesize],classmate1[i]);
strcpy(classmate2[classmatesize],classmate2[j]);
classmatesize++;
}
}
}
}
int main(void) {
int i;
classmate1 = malloc(1000 * sizeof(char*));
for ( i = 0; i < 1000 ; i++)
classmate1[i] = malloc((1000) * sizeof(char));
classmate2 = malloc(1000 * sizeof(char*));
for ( i = 0; i < 1000 ; i++)
classmate2[i] = malloc((1000) * sizeof(char));
yyparse();
checkclassmates();
print_the_array();
return 0;
}
my yyparse(); if i print the classmate1 and classmate2 by commenting the checkclassmates function its printing and clasematesize is printing as 7
classmate1
[ sania pawan pandu haldiram manas abhi prince ]
classmate2
[ sam pandu madhur arjun jyoti ash sam ]
proplem is with strcpy only if i comment the strcpy instructions its working fine its giving segmentation fault.
i even tried sprintf instead of strcpy still i cannot figure it out.
Upvotes: 0
Views: 128
Reputation: 206567
My hunch is that the lines
classmatesize++;
in checkclassmates
are the culprits. There are four of them. Since you are are incrementing classmatesize
inside the loops, the conditional of the if
statements never fail and you end up accessing the arrays out of bounds.
Try removing those lines and see whether the problem is still there.
Upvotes: 5