strtok函数读写冲突问题

先上测试代码

#include "stdafx.h"
#include <iostream>
using namespace std;

int _tmain(int argc, _TCHAR* argv[])
{
    const char* split = ";";
    char* str = "Hello;world;";
    //result = NULL;
    char* result = strtok(str, split);
    cout << result;
    cin.get();

    return 0;
}

运行后

strtok函数在运行时,报堆栈读写冲突问题,后来看到strtok.c源文件里面对字符串的操作如下

 /* Find 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++ = '';
                        break;
                }

函数原理是,在函数执行中,当遇到分隔符的时候,会在原字符串查找到分隔符的位置自动替换成空字符,看来是字符串有问题,strtok()会改字符串内容,char *str = "Hello;world;";实际上先是在文字常量区分配了一块内存放"Hello;world;",然后在栈上分配一地址给str,并指向这块地址,然后改变常量";"自然会崩溃,然后改了一下代码

#include "stdafx.h"
#include <iostream>
#include <cstring>
using namespace std;

int _tmain(int argc, _TCHAR* argv[])
{
    const char* split = ";";
    char str[] = "Hello;world;";
    //result = NULL;
    char* result = strtok(str, ";");
    cout << result;
    cin.get();

    return 0;
}

将原有的char * str="Hello;world;";改成char str[] = "Hello;world;";因为后者的字符串数据并不是放在常量区,所以可以修改,所以就不报错了

原文地址:https://www.cnblogs.com/djzny/p/4432453.html