【问题标题】:strtok() is not responding in netbeans IDEstrtok() 在 netbeans IDE 中没有响应
【发布时间】:2016-05-26 14:58:15
【问题描述】:

我正在测试 netbeans 8.1 中的 explode() 函数。 如下:

array explode(const char * delimiter, const char * str, unsigned int limit = 0){
        
        array out;                 //my custom struct 
        
        str = strtok(const_cast<char*>(str), delimiter);
        int tokens = 0; 
        
        while(str){
            cout << str;    //this line is my nightmere, as it does not display
            str = strtok(NULL, delimiter);
            out[tokens + 1] = str;

            tokens++;
	}     
        
        return out;
   }

以上 sn-p 在 netbeans 8.1 中构建成功。但是,在运行时,错误消息是:

cygdrive/C/Program Files/NetBeans 8.1/ide/bin/nativeexecution/dorun.sh:第 33 行:6036 分段错误(核心转储)sh "${SHFILE}" 按 [Enter] 关闭终端...

【问题讨论】:

  • 你是怎么调用这个函数的?你传入了什么数据?
  • 像这样:array result = explode(",", "Socket, send, 1 2 3");
  • 您正在尝试写入只读字符串文字,即使您 const_cast 它...使用不同的 char* 来保存 strtok 的返回值的原始指针。

标签: c++ netbeans


【解决方案1】:

所以你问题的关键是这个,来自评论:

array result = explode(",", "Socket, send, 1 2 3");

意味着const char * 是一个字符串文字,可能分配在可执行文件的初始化数据段中,并且映射为只读。这意味着您的程序确实不能更改文字的内容,并且像您一样使用const_cast 是非法的。

您应该能够调查您的错误消息告诉您创建的核心文件,您会发现在strtok 内部它试图将零写入您的字符串,以终止第一个令牌,但失败了,因为不允许写入该内存。

总结:你不能使用const_cast 来使某些东西真正不可写。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-06-03
    • 2019-10-10
    • 2015-12-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多