使用void指针分配内存 [英] Memory allocation with void pointer
问题描述
此代码是否删除了适量的内存:
struct SAMPLE {
int a,b,c;
char zzz;
};
void * ptr;
int main()
{
ptr =(void *)new [SAMPLE];
delete ptr; //删除空指针而不强制它
}
" Maedowan" <马****** @ gaz.pl>在消息中写道
news:ch ********** @ inews.gazeta.pl ...此代码是否删除了适量的内存:
struct SAMPLE {
int a,b,c;
char zzz;
};
void * ptr;
int main()
{
ptr =(void *)new [SAMPLE];
删除ptr; //删除void指针而不进行转换
}
不,这个程序的行为完全由C ++定义
标准。可能没问题,可能没有。
john
John Harrison写道:
Maedowan <马****** @ gaz.pl>在消息中写道
新闻:ch ********** @ inews.gazeta.pl ...此代码是否删除了适量的内存:
struct SAMPLE {
int a,b,c;
char zzz;
};
void * ptr;
int main( )
{
ptr =(void *)new [SAMPLE];
删除ptr; //删除void指针而不强制它
}
不,C ++
标准完全没有定义该程序的行为。它可能没问题,也可能没有。
但是free和malloc呢,他们使用void *指针并且做得对。
" Maedowan" <马****** @ gaz.pl>在消息中写道
news:ch ********** @ inews.gazeta.pl ...John Harrison写道:
< blockquote class =post_quotes>
Maedowan <马****** @ gaz.pl>在消息中写道
新闻:ch ********** @ inews.gazeta.pl ...此代码是否删除了适量的内存:
struct SAMPLE {
int a,b,c;
char zzz;
};
void * ptr;
int main( )
{
ptr =(void *)new [SAMPLE];
删除ptr; //删除void指针而不强制它
}
不,C ++
标准完全没有定义该程序的行为。它可能没问题,也可能不行。
但是free和malloc呢,他们使用void *指针做对了。
免费和malloc会没事的。没有理由你不能在C ++
计划中使用它们。
john
>
Does this code delete right amount of memory:
struct SAMPLE{
int a,b,c;
char zzz;
};
void* ptr;
int main()
{
ptr=(void*) new[SAMPLE];
delete ptr; //delete void pointer without casting it
}
"Maedowan" <Ma******@gaz.pl> wrote in message
news:ch**********@inews.gazeta.pl...Does this code delete right amount of memory:
struct SAMPLE{
int a,b,c;
char zzz;
};
void* ptr;
int main()
{
ptr=(void*) new[SAMPLE];
delete ptr; //delete void pointer without casting it
}
No, the behaviour of this program is completely undefined by the C++
standard. It might be OK, it might not.
john
John Harrison wrote:
"Maedowan" <Ma******@gaz.pl> wrote in message
news:ch**********@inews.gazeta.pl...Does this code delete right amount of memory:
struct SAMPLE{
int a,b,c;
char zzz;
};
void* ptr;
int main()
{
ptr=(void*) new[SAMPLE];
delete ptr; //delete void pointer without casting it
}
No, the behaviour of this program is completely undefined by the C++
standard. It might be OK, it might not.
but what about free and malloc, they use void* pointers and does it right.
"Maedowan" <Ma******@gaz.pl> wrote in message
news:ch**********@inews.gazeta.pl...John Harrison wrote:
"Maedowan" <Ma******@gaz.pl> wrote in message
news:ch**********@inews.gazeta.pl...Does this code delete right amount of memory:
struct SAMPLE{
int a,b,c;
char zzz;
};
void* ptr;
int main()
{
ptr=(void*) new[SAMPLE];
delete ptr; //delete void pointer without casting it
}
No, the behaviour of this program is completely undefined by the C++
standard. It might be OK, it might not.
but what about free and malloc, they use void* pointers and does it right.
free and malloc would be fine. There''s no reason you can''t use them in a C++
program.
john
这篇关于使用void指针分配内存的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!