I was debugging some C code that was giving me a segmentation fault. I was trying to localize the issue by using printf()s.
However, even though I scoped the issue between two printf()s, I couldn't deduce the problem, because what was between these two printf()s was just a simple pointer declaration.
Finally, I used gdb to actually debug and see what's happening. I found that the Segmentation fault was as a result of an infinite loop somewhere down the line way past the second printf().
I always thought that using **printf()**s to localize seg-faults was an easy way out for simple programs. But seems not.
Can someone explain the behavior? Is it as a result of some sort of compiler optimization? Or has it something to do with the structure of my code itself?
The code I was testing is as below.
The Seg-Fault happens between the ----BEGIN----- and ----END----- printf calls.
The actual issue is in the last while loop which becomes an infinite loop.
I hope this is a legit question and not asked before.
void Replace(char *name,char *newname,char record[]) {
printf("CAME\n");
char *tempRecord = record;
printf("This too\n");
char *newRecord = newname;
printf("----BEGIN-----\n");
char *q;
printf("----END-----\n");
int i = 0;
printf("HERE 1");
while(*(tempRecord+i) != '\0') {
if(*(tempRecord+i) == ','){
q = tempRecord+i;
break;
}
i++;
}
int j = 0;
printf("HERE 2");
while(j >= 0) {
if(*(newname + j) == '\0') {
break;
}
j++;
}
int a =0;
printf("HERE 3");
while (*(q+a) != '\n') {
*(newname + j + a) = *(q+a);
a++;
}
printf("HERE 4");
int b = 0;
while (*newname != '\n'){
*(record + b) = *(newname + b);
b++;
}
printf("%s",record);
}
EDIT: Adding more source code
void main(void) {
char arrayName[100];
char arrayNewname[100];
char *name = arrayName;
char *newname = arrayNewname;
char record[1000];
printf("Please enter a name in the phonebook: ");
scanf("%s",name);
printf("Please enter the replacement name: ");
scanf("%s",newname);
FindRecord("PhoneBook.csv",name,record);
// records in csv are formatted as: "Bobby, 26, 5145480546"
// The above method copies the matching record in csv into record[]
printf("%s\n",record);
Replace(name, newname,record);
}
Thank You
Shabir