[英]Why strtok_s works when I use StrDup?
I use strtok_s with an allocated string. 我将strtok_s与分配的字符串一起使用。
The code above handles an exception: 上面的代码处理一个异常:
char *string1 = NULL;
string1 = (char*)LocalAlloc(LPTR, 100 * sizeof(char));
// TODO: Verify if string1 != NULL
string1 = "A string\tof ,,tokens\nand some more tokens";
token1 = strtok_s(cp1, seps, &next_token1);
But when I call StrDup, my code works: 但是当我调用StrDup时,我的代码可以正常工作:
cp1 = StrDup(string1);
token1 = strtok_s(cp1, seps, &next_token1);
However my understanding of StrDup is it uses LocalAlloc to allocate storage space for the copy of the string (according to MSDN ). 但是我对StrDup的理解是它使用LocalAlloc为字符串的副本分配存储空间(根据MSDN )。
So, what is wrong in my first example ? 那么,我的第一个示例出了什么问题? How to correct this code without using StrDup ? 如何在不使用StrDup的情况下更正此代码?
string1 = (char*)LocalAlloc(LPTR, 100 * sizeof(char));
// TODO: Verify if string1 != NULL
string1 = "A string\tof ,,tokens\nand some more tokens";
token1 = strtok_s(cp1, seps, &next_token1);
You've overwritten your pointer... it starts out NULL and you make it point to allocated space (which is your intention), but you then change it to point to something that is read-only, ac string constant. 您已经覆盖了指针...指针开始为NULL,并使其指向已分配的空间(这是您的意图),但是随后将其更改为指向只读的,交流字符串常量的东西。 Since strtok_s
needs to be able to write into the buffer, this makes it fail. 由于strtok_s
需要能够写入缓冲区,因此使其失败。 When you strdup()
instead, you create another (writable) copy of the string. 当您使用strdup()
,将创建该字符串的另一个(可写)副本。
Instead of setting string1 = "some constant string";
而不是设置string1 = "some constant string";
you can use strcpy()
(one of its length-limiting versions, for safety) to copy the read only string constant into your buffer. 您可以使用strcpy()
(为安全起见,它是长度限制的版本之一)将只读字符串常量复制到缓冲区中。 This gets you where you need to be without strdup()
, but since strdup()
performs the allocation for you, your work would be easier by going to it directly and cutting out the allocation / copy. 这使您无需使用strdup()
就可以到达strdup()
,但是由于strdup()
为您执行分配,因此直接进行处理并剪切分配/副本会strdup()
您的工作。
This line 这条线
string1 = "A string\tof ,,tokens\nand some more tokens";
doesn't do what you expected it to. 并没有达到您的预期。
You wanted to write the contents of the constant string into the memory buffer pointed to by string1
. 您想将常量字符串的内容写入string1
指向的内存缓冲区。 What you actually did was change the value of string1
to point at memory that was allocated by the compiler to hold the constant string. 您实际上所做的是将string1
的值更改为指向编译器分配的用于保存常量字符串的内存。
One way of doing what you wanted is 做您想要的一种方法是
strcpy(string1, "A string\tof ,,tokens\nand some more tokens");
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.