c语言 函数 内存溢出,c - 除非我调用printf()函数,否则C代码会卡住 - 堆栈内存溢出...

我有一个代码可以读取文本文件,对其中的单词进行标记,然后仅从文本中选择唯一的单词,然后将它们连接起来并使用puts()函数进行打印。 这是完整的代码:

#include

#include

#include

char str_array[100][100];

char output[100];

void concatenate(int index)

{

// compares output with empty string

if (!strcmp(output, ""))

{

strcpy(output, str_array[index]);

}

else //else existing string is contcatenated

{

strcat(output, " "); // add space

strcat(output, str_array[index]);

}

}

void unique_selection(char file[])

{

FILE *F = fopen(file, "r");

char ch; char str[100];

int i=0, j=0;

while ((ch=getc(F)) != EOF)

{

// if space or newline is detected i.e. word is finished

if (ch == ' ' || ch == '\n')

{

//traverse array of strings

for(int x=0; x

{

//if current str is already in array, skip appending

if (!strcmp(str_array[x], str)) goto ELSE;

}

strcpy(str_array[j], str);

j++;

ELSE:

i=0;

memset(str, 0, strlen(str));

}

else //otherwise chars of a word get appended to string array

{

str[i] = ch;

i++;

}

}

for(int k=0; k

{

concatenate(k);

}

puts(output);

fclose(F);

}

int main(void) {

char file[] = "test.txt";

//printf("Output:");

unique_selection(file);

return 0;

}

该代码可以正常工作,但是每次遇到尝试打印输出字符串(使用puts()或printf("%s") ,程序都会卡住,这与循环永远迭代时发生的情况类似,但我遇到了一个奇怪的问题。奇怪的是,通过将printf放在函数调用之前解决了这个问题,如果我从函数中删除puts() ,即使main()有或没有printf,代码也可以正常运行。

为什么会这样呢?