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,代码也可以正常运行。

为什么会这样呢?

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值