简体   繁体   中英

Stack Smashing Detected upon input fgets

The purpose is to enter string1 and string2 and remove any occurrence of any of the letters in string2 from string1. I get a stack smashing detection error after I input my second string. The function rmchr works fine. It's once we get to 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++;
      }

    }

  }
}

sample 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)

In 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++;
      }

    }

You count value is always incremented in this loop of loop and can be bigger than the maximum allowed value of 99 (the last element of word array). For example if s is 12, then s - 2 * s - 2 will give count to 100 .

Moreover at first glance it seems you forgot to use l in the second loop using s instead.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM