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;
}
6
  • 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="";? Commented Jan 31, 2012 at 1:14
  • @Vyktor: void main might work in practice, but it's not legal. Commented Jan 31, 2012 at 1:15
  • @jamesdlin: under C89, void main could be allowed. But regardless, it's not a good idea. Commented Jan 31, 2012 at 1: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(). Commented Jan 31, 2012 at 1:31
  • 2
    @Vyktor: This was discussed on StackOverflow before, here, 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. Commented Jan 31, 2012 at 1:51

1 Answer 1

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

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.