0

I made this little program to count how many 'en's there are in a string. It does work, but I get an error saying there's stack smashing detected. I do not understand how to solve this... Can anyone give me a tip?

#include <stdio.h>
#include <stdlib.h>
#include <string.h>


int main(int argc, char *argv[])
{
char s[30];
int getal=0, e, n;
int i = 0;

gets(s);

for (; s[i] != '\0'; i++) {
     e =(s[i] == 'e');
     n =(s[i + 1] == 'n');

     if (e && n)
         getal++;
}

printf("Het aantal bedraagt: %i", getal);

return 0;
}
Bathsheba
  • 231,907
  • 34
  • 361
  • 483
jib
  • 13
  • 1
  • 2
    Is the string you input longer than 29 characters? Then `gets` will happily write way beyond the bounds of the passed array. There's a reason that `gets` have removed from the latest C standard, use [`fgets`](http://en.cppreference.com/w/c/io/fgets) (or [`gets_s`](http://en.cppreference.com/w/c/io/gets)) instead. – Some programmer dude Jan 07 '14 at 10:30
  • 1
    http://stackoverflow.com/questions/1345670/stack-smashing-detected might help you understand the issue – SoulRayder Jan 07 '14 at 10:31
  • I fixed some particularly nasty indenting so we can see the wood from the trees. – Bathsheba Jan 07 '14 at 10:34
  • Thank you. The array length was indeed the problem. Really stupid of me to not notice such a stupid mistake. I will look up about fgets, have not used it before. Once again, thank you. – jib Jan 07 '14 at 10:35
  • s[i+1] could still look beyond array bounds try only checking it if you're not on the last element. – sdf Jan 07 '14 at 10:38

1 Answers1

3

Never use gets(), it's vulnerable to buffer overflow.

Use the much safer alternative fgets(), like so:

char buf[256];

if(fgets(buf, sizeof buf, stdin) != NULL)
{
  /* process string here */
}
unwind
  • 391,730
  • 64
  • 469
  • 606
  • Oh, I see. I will try to work with that in the future. Thanks! Got the problem solved already though. – jib Jan 07 '14 at 10:38