2

I was trying to mimic strtok functionality but getting segmentation fault. Please help me out here.

Here is my code:

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

int main(int argc, char argv[])
{
    int i=0;
    char c[]="get the hell out of here";
    char *p;
    char *temp=(char *)malloc(100);
    while(c[i]!='\0')
    {
        if(c[i]!=' ')
        {
            *temp=c[i];
            temp++;
            i++;
        }
        else
        {
            *temp='\0';
            printf("printing tokenn");
            puts(temp);
            i++;
            temp="";
        }
    }
    return 0;
}
simon
  • 12,666
  • 26
  • 78
  • 113
pavan
  • 77
  • 1
  • 9
  • 1
    @dreamlax void main is actually okay, Shashank can you please move `#include` into code and format it properly? And what do you mean by line `temp="";`? – Vyktor Jan 31 '12 at 01:14
  • @Vyktor: `void main` might work in practice, but it's not legal. – jamesdlin Jan 31 '12 at 01:15
  • @jamesdlin: under C89, void main could be allowed. But regardless, it's not a good idea. – Joe Jan 31 '12 at 01:27
  • An implementation *may* permit `void main()`. If you're using a compiler that doesn't support and document it, then the program's behavior is undefined. Unless you're compiling for a freestanding implementation, there is *no* good reason to use `void main()`. – Keith Thompson Jan 31 '12 at 01:31
  • 2
    @Vyktor: This was discussed on StackOverflow before, [here](http://stackoverflow.com/questions/8844915/what-happens-if-main-does-not-return-an-int-value), where it was found that the C and C++ standard actually require `int` as the return type. The only implementation-defined aspect of `main` are the arguments. – dreamlax Jan 31 '12 at 01:51
  • There are some systems that use `void main()`, such as Plan 9, so unless you are developing for one of those, `int main()` is a substantially better choice. – dreamlax Jan 31 '12 at 01:52

1 Answers1

8
temp="";

This causes temp to point at unmodifiable memory, leading to a fault the next time you try to modify through it. You wanted to restore temp to the value you got from malloc (which you forgot to save).

David Schwartz
  • 179,497
  • 17
  • 214
  • 278