以下代码在运行时在第L2行引发访问冲突,这发生在第二次调用setword期间。
Q>在L2中哪里出错了,为什么第一行的第一个memset没有问题?
注意:我试图将问题区域与更大的代码隔离开来,希望这能提供足够的信息。
void setword( char ** word )
{
if ( *word == NULL )
{
*word = (char *)malloc(30);
memset( *word, '\0', 30 ); //L1: OK
}
else
{
memset( *word, '\0', 30 );//L2: Access violation
}
*word = "Hello";
//*word shall be freed when operations are complete.
}
int main()
{
char * word = NULL;
setword( &word ); //Call 1: OK
printf( "%s\n", word );
setword( &word ); //Call 2: NOK!
printf( "%s\n", word );
}
答案 0 :(得分:5)
*word = (char *)malloc(30);
[...]
*word = "Hello";
第二个赋值产生内存泄漏(你丢失了malloc返回的指针),并使word
指向可能的只读内存 - 对它的任何写访问都将导致未定义的行为。
(例如,请参阅此问题:Is modification of string literals undefined behaviour according to the C89 standard? - 在您的情况下,"Hello"
是一个字符串文字。您使word
指向第二个分配的那个。所以你不能修改word
之后指向的数据。)
使用strcpy
将"hello"
复制到动态分配的缓冲区。
答案 1 :(得分:0)
您应该知道*word = "Hello"
后,*word
的值是常量区域,您可以更改此区域的内容。