指针立即0x0

时间:2010-11-30 10:45:38

标签: c++ pointers gtkmm

我有这个代码。指针在使用之前立即变为0x0。很久以前,它有正确的地址。

TreeViewColumn *col;
col = preview->get_column(pcFolder); /* col = 0x7fff5fc404a0 */
col->set_resizable(true);            /* col = 0x0 */

我使用Gtkmm 2.4,但它返回预期值,它只是变成0x0。怎么了?

gdb证明:

151             col = preview->get_column(pcFolder); /* col = 0x7fff5fc404a0 */
(gdb) print col
$1 = ('Gtk::TreeViewColumn' *) 0x7fff5fc404a0
(gdb) print *col
warning: can't find linker symbol for virtual table for `Gtk::TreeViewColumn' value
$2 = {
  <Gtk::Object> = {
    <Glib::Object> = {
      <Glib::ObjectBase> = <invalid address>, 
      members of Glib::Object: 
      _vptr$Object = 0x7fff5fc06a20, 
      static object_class_ = {<No data fields>}
    }, 
    members of Gtk::Object: 
    static object_class_ = {<No data fields>}, 
    referenced_ = 21, 
    gobject_disposed_ = 60
  }, 
  members of Gtk::TreeViewColumn: 
  static treeviewcolumn_class_ = {<No data fields>}
}
(gdb) next
152             col->set_resizable(true);            /* col = 0x0 */
(gdb) print col
$3 = ('Gtk::TreeViewColumn' *) 0x0
(gdb) print *col
Cannot access memory at address 0x0
(gdb) next

Program received signal EXC_BAD_ACCESS, Could not access memory.
Reason: KERN_INVALID_ADDRESS at address: 0x0000000000000000
0x00000001000edc68 in Gtk::TreeViewColumn::set_resizable ()

我不知道是什么原因引起这种现象。你有吗?

解决方案: 阅读文档。返回pcFolder的函数从1开始计数,get_column()从0开始计算。

4 个答案:

答案 0 :(得分:3)

函数调用:

preview->get_column(pcFolder);

返回NULL。

当gdb显示当前代码行时,在您键入next。之前它尚未执行。

您可能传递的索引大于preview中的列数。尝试:

p pcFolder
p preview->get_columns().size()

答案 1 :(得分:2)

preview->get_column();返回NULL,在此之前,它只是一些随机值,因为你没有初始化col变量

答案 2 :(得分:2)

更好的代码实际上是在使用时通过在声明点调用getColumn来立即初始化变量:

TreeViewColumn *col = preview->get_column(pcFolder);

如果此函数可以返回NULL(如图所示),则必须在使用指针之前进行检查,因此:

if( col != NULL )
{
   col->set_resizable( true );
}
// else handle the "error" if you want

答案 3 :(得分:1)

preview->get_column(pcFolder)

必须返回0。