Casz146 Casz146 - 4 months ago 8
C Question

Skipping entire "for loop" when adding code inside the loop

I'm a beginner to C and have been trying to develop a few programs, but I'm currently stuck. The problem is as follows: When I run the code below, it skips over the whole "Type your name" part and skips immediately so the "Type your CPF" part.

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

void append(char subject[], const char insert[], int pos) {
char buf[100] = {};

strncpy(buf, subject, pos);
int len = strlen(buf);
strcpy(buf+len, insert);
len += strlen(insert);
strcpy(buf+len, subject+pos);

strcpy(subject, buf);
}

int main() {
int i,j;
char name[21],filename[21],cpf[16];
FILE *fp;

for ( ;strlen(name)<3; ) {
name[0] = 0;
printf("Type your name (max characters: 20, no numbers allowed) \n");
fflush (stdout);
fgets(name,21,stdin);
for(i=0; name[i]!='\0'; ++i) {
while (!((name[i]>='a'&&name[i]<='z') || (name[i]>='A'&&name[i]<='Z' || name[i]=='\0'))) {
for(j=i;name[j]!='\0';++j) {
name[j]=name[j+1];
}
name[j]='\0';
}
}
strtok(name, "\n");
strcpy(filename,name);
strcat(filename, ".txt");
}
fp = fopen(filename,"a");
fprintf(fp,"Name:");
fprintf(fp, name);
fflush(stdin);

for ( ;strlen(cpf)<11 || strlen(cpf)>11; ) {
printf("Please enter your CPF, consisting of 11 numbers:\n");
scanf("%s",&cpf);
}
append(cpf,".",3);
append(cpf,".",7);
append(cpf,"-",11);
fprintf(fp,"\nCPF: ");
fprintf(fp, cpf);
system("pause");
}


However, when I comment the part below it runs normally.

// for(i=0; name[i]!='\0'; ++i) {
// while (!((name[i]>='a'&&name[i]<='z') || (name[i]>='A'&&name[i]<='Z' || name[i]=='\0'))) {
// for(j=i;name[j]!='\0';++j) {
// name[j]=name[j+1];
// }
// name[j]='\0';
// }
// }


As you can see, I want the code to remove all extra characters from the name and just make the name alphabetical characters, but I'm not sure why it skips the whole "for-loop" when I enter this particular part.

Any suggestions? Also since I'm new to C I may have included too much code, feel free to tell me and I'll remove irrelevant parts.

Answer

Lets look at these two lines:

char name[21],filename[21],cpf[16];
...
for ( ;strlen(name)<3; ) {

First you declare the array name (and some others), but you don't initialize it. Then you use the uninitialized in a call to strlen. That will lead to undefined behavior because the contents of name is indeterminate.

You must explicitly initialize the array, or any other local variables, before you use it.

Simplest way is doing something like

char name[21] = "", ...;

As for why the code behaves differently in different situation is because of the undefined behavior. Undefined behavior is, by its very definition, undefined. It means just about anything can happen, even to seemingly work fine. It could also crash or cause nasal demons.