堆栈粉碎在输入fgets时检测到

时间:2015-09-23 20:40:57

标签: c arrays string function fgets

目的是输入string1和string2并从string1中删除string2中任何字母的出现。输入第二个字符串后,我得到一个堆栈粉碎检测错误。函数rmchr工作正常。一旦我们到达rmstr。

main.c中:

#include <stdio.h>
#include "rmstr.h"

int main()
{
  int ch, l;
  char x[3];
  x[0]='y';

  while(x[0]=='y'||x[0]=='Y')
  {
    char string[100]={0}, string1[100]={0}, string2[100]={0}, c[3];

    printf("Enter a String: ");
    fgets(string, 100, stdin);
    if (string[98] == '\n' && string[99] == '\0') { while ( (ch = fgetc(stdin)) != EOF && ch != '\n'); }

    printf("Enter a Char: ");
    fgets(c, 2, stdin);
    while ( (ch = fgetc(stdin)) != EOF && ch != '\n');

    rmchr(string, c[0]);

    printf("Enter a String: ");
    fgets(string1, 100, stdin);
    if (string1[98] == '\n' && string1[99] == '\0') { while ( (ch = fgetc(stdin)) != EOF && ch != '\n'); }


    printf("Enter the second string: ");
    fgets(string2, 100, stdin);
    if (string2[98] == '\n' && string2[99] == '\0') { while ( (ch = fgetc(stdin)) != EOF && ch != '\n'); }

    rmstr(string1, string2);

    printf("Run Again?(y/n):");
    fgets(x, 2, stdin);
    while ( (ch = fgetc(stdin)) != EOF && ch != '\n');
  }

 return 0;
} 

functions.h:

rmchr(char *string, char c)
{ 
  int i=0, j=0, count=0;
  char word[100]={0};

  int s = strlen(string);

  for(i=0; i<=(s-2); i++)
  {
    if(string[i] != c && string[i] != ' ')
    {
      word[count] = string[i];
      count++;
    }    
  }

  printf("Word: ");
  for(i=0; i<=count; i++)
  {
    printf("%c", word[i]); 
  }
  printf("\n"); 
}

rmstr(char *string1, char *string2)
{
   int i=0, j=0, count=0;
   char word[100]={0};

   int s = strlen(string1);
   int l = strlen(string2);

   for(i=0; i<=(s-2); i++)
   {
    for(j=0; j<=(s-2); j++)
    {
      if(string1[i] != string2[j] && string1[i] != ' ')
      {
        word[count] = string1[i];
        count++;
      }

    }

  }
}

示例outpput:

Enter a String: Ahhaha
Enter a Char: h
Word: Aaa
Enter a String: Annabcdcbcdbckje
Enter the second string: n
*** stack smashing detected ***: ./q4 terminated
Aborted (core dumped)

1 个答案:

答案 0 :(得分:0)

rmstr

  for(i=0; i<=(s-2); i++)    {
    for(j=0; j<=(s-2); j++)
    {
      if(string1[i] != string2[j] && string1[i] != ' ')
      {
        word[count] = string1[i];
        count++;
      }

    }

count值总是在此循环循环中递增,并且可能大于99的最大允许值(word数组的最后一个元素)。例如,如果s为12,那么s - 2 * s - 2会将count提供给100

此外,乍一看,似乎您忘记在第二个循环中使用l代替s