STRTOK crashes saying access viiolation

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • Toufiq S
    New Member
    • Feb 2012
    • 2

    #1

    STRTOK crashes saying access viiolation

    heres the piece of code
    Code:
    void main()
    {
    	char *trial = "((100,1,101),(11,1,12))";
    	char *t1;
    	int n;
    	
    for ( t1 = strtok(trial,",");
          t1 != NULL;
          t1 = strtok(NULL, ",") )
    {	//n =	atoi("100");// a = strtok(trial," ");
    	printf("\n%s",t1);}
    	//printf("\n%d",n);
    	getch();
    }
    But it works fine if array is used that is
    char trial[] = "((100,1,101),( 11,1,12))";

    Can anybody tell me wats the cause of that?
    Last edited by Banfa; Feb 28 '12, 09:48 AM. Reason: Added [code]...[/code] tags round the code, please use them in future
  • weaknessforcats
    Recognized Expert Expert
    • Mar 2007
    • 9214

    #2
    Code:
    t1 != NULL;    <-------?
     t1 = strtok(NULL, ",") )
    etc...
    Have you, by any chance. omitted the if and it's braces?

    Comment

    • Toufiq S
      New Member
      • Feb 2012
      • 2

      #3
      Hi,

      Those three statements are part of the for loop condition split in 3 lines.

      Well it works fine just if I change char *t1 to char t1[]..

      Comment

      • Banfa
        Recognized Expert Expert
        • Feb 2006
        • 9067

        #4
        strtok writes to the buffer that you provide in order to create the return strings.

        When you use char* you are passing a pointer to string constant. Your platform has every write to make string constants constant which would cause an issue when strtok tries to write to it.

        However when you use char[] the compiler allocates a buffer for you (on the stack in this case). Since your program owns the buffer and has declared it non-const it is placed in writeable memory and there will be no problem when strtok trys to write to it.

        Comment

        Working...