strtok function Read-write conflict problem

Source: Internet
Author: User
Tags strtok

Test the Code First

#include"stdafx.h"#include<iostream>using namespacestd;int_tmain (intARGC, _tchar*argv[]) {    Const Char* Split =";"; Char* str ="Hello;world;"; //result = NULL;    Char* result =strtok (str, split); cout<<result; Cin.Get(); return 0;}

After running

Strtok function at run time, reported the stack read-write conflict problem, later see STRTOK.C source file in the face of the string operation as follows

 /*   Find the-the-end of the token. If It is not the end of the string, * put a null there.  */ for  (; *str; Str++)  if  (map[*str >> 3] & (1  << (*str & 7   *str++ =  " \0 " ;                 break  ; }

The function principle is, in the function execution, when encounters the delimiter, will be in the original string to find the delimiter position automatically replaces the null character, appears to be the string has the question, strtok () will change the string content, char *str = "hello;world;"; In fact, first in the literal constant area allocated a piece of "Hello;world;", and then on the stack to assign an address to STR, and point to the address, and then change the constant ";" Naturally crashes and then changes the code

#include"stdafx.h"#include<iostream>#include<cstring>using namespacestd;int_tmain (intARGC, _tchar*argv[]) {    Const Char* Split =";"; CharStr[] ="Hello;world;"; //result = NULL;    Char* result = Strtok (str,";"); cout<<result; Cin.Get(); return 0;}

The original char * str= "hello;world;"; Change to char str[] = "hello;world;"; Because the latter string data is not placed in the constant area, so can be modified, so there is no error.

strtok function Read-write conflict problem

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.