UNIX wc 명령의 간단한 구현을 수행하고 있으며 매우 이상한 문제가 있습니다. 49 행에서 printf를 제거하면 프로그램이 제대로 작동하지 않습니다. 나는 많은 일을 시도했지만 그들 중 누구도 일하지 않았습니다. 프로그램은 작동하지만 출력물은 내가 원하는 것이 아니라 원하는 것입니다.printf의 C 프로그램의 비정상적인 동작
#include<stdio.h>
#include<stdlib.h>
#include<fcntl.h>
#include <string.h>
#include<errno.h>
#include<sys/stat.h>
int *counter(FILE* file) {
// Function counter - counts the number of lines, words and symbols
int nsymbols = 0, nwords = 0, nlines = 0;
char c;
while (EOF != (c = fgetc(file))) {
nsymbols++;
if(c == ' '){
nwords++;
}
if(c == '\n'){
nlines++;
nwords++;
}
}
int count[] = {nlines, nwords, nsymbols};
return count;
}
int main(int argc,char* argv[]) {
if(argc == 1) {
int *counted;
counted = counter(stdin);
printf("\t%d \t%d \t%d\n", counted[0], counted[1], counted[2]);
}
else{
int i,k, bool = 0;
int total[] = {0,0,0};
char c = ' ', w = ' ', l = ' ';
for(i = 1; i < argc; i++) {
// Cheking if there are some options activated
if(strchr(argv[i], '-')){
if(strcmp(argv[i], "-")==0){
continue;
}
if(strchr(argv[i], 'l')) {
l = 'l';
}
if(strchr(argv[i], 'w')) {
w = 'w';
}
if(strchr(argv[i], 'c')){
c = 'c';
}
bool = 1;
}
}
if(!bool) {
// If none of them are activated from the user, automatically activates all of them
l = 'l';
w = 'w';
c = 'c';
}
printf("%c %c %c", l,w,c);
for(i = 1; i<argc; i++){
if(strcmp(argv[i], "-") == 0){
int *counted;
counted = counter(stdin);
for(k = 0; k < 3; k++){
total[k] += counted[k];
}
if(l == 'l')
printf("\t%d", counted[0]);
if(w == 'w')
printf("\t%d", counted[1]);
if(c == 'c') {
printf("\t%d", counted[2]);
}
printf(" %s\n", "-");
}
else{
if(strchr(argv[i], '-'))
continue;
FILE* file = fopen(argv[i], "r");
if(file == NULL) {
fprintf(stderr, "%s : %s\n", argv[i], strerror(errno));
return 1;
}
struct stat checker;
if(stat(argv[i], &checker) < 0) {
return 2;
}
if(checker.st_mode & S_IRUSR) {
}
else{
fprintf(stderr, "%s : %s\n", argv[i],strerror(EACCES));
return 3;
}
int *counted;
counted = counter(file);
for(k = 0; k < 3; k++){
total[k] += counted[k];
}
if(l == 'l')
printf("\t%d", counted[0]);
if(w == 'w')
printf("\t%d", counted[1]);
if(c == 'c') {
printf("\t%d", counted[2]);
}
printf(" %s\n", argv[i]);
}
}
if(l == 'l')
printf("\t%d", total[0]);
if(w == 'w')
printf("\t%d", total[1]);
if(c == 'c') {
printf("\t%d", total[2]);
}
printf(" total\n");
}
return 0;
}
프로그램이 끝날 때까지 유지하고 있기 때문에 ...의 malloc 또는은 calloc을 통해 동적 메모리 할당을 사용하여 작성 'counter'의 _local_ 배열. 이것은 정의되지 않은 동작입니다. –
49 호가 어느 것입니까? –