2010-09-02 181 views
1

C++函数,的strtok()cplusplus.com的strtok - 缓冲区溢出

将本实施例中苦于缓冲区溢出如果STR未正确结束?

/* strtok example */ 
/* source - cplusplus.com (see link below) */ 
#include <stdio.h> 
#include <string.h> 

int main() 
{ 
    char str[] ="- This, a sample string."; 
    char * pch; 
    printf ("Splitting string \"%s\" into tokens:\n",str); 
    pch = strtok (str," ,.-"); 
    while (pch != NULL) 
    { 
    printf ("%s\n",pch); 
    pch = strtok (NULL, " ,.-"); // walk the stack? 
    } 
    return 0; 
} 

如果STR不以 “\ 0” 正确端接,是不是有可能

pch = strtok (NULL, " ,.-"); 

走栈?

谢谢!

+2

想到这一点的简单方法是,如果'str'没有正确终止,那么*它不是C风格的字符串*。这只是一些人物。当然,将C字符串以外的任何内容传递给'strtok'都是坏消息。 – 2010-09-02 21:22:15

+0

这是为了一些白帽子黑客? – Chubsdad 2010-09-03 04:39:27

回答

1

如果字符串不是以空字符结尾的,那么大多数字符串处理函数将走到最后。

但是,在您的代码示例中str已终止。

+0

罗杰。我的例子显示它,但如果我使用的函数没有字符串终止,可能会发生缓冲区溢出。 谢谢! – 2010-09-02 21:06:39