为什么共享库中的分配内存无法被应用程序访问? [英] Why might malloc'd memory from a shared library be inaccessible to the application?

查看:95
本文介绍了为什么共享库中的分配内存无法被应用程序访问?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我维护了一个用C编写的库,Linux上的用户可以使用加载共享库和调用函数的模块直接从Python访问该库.该模块是共享库的此版本中最常用的模块,人们正在使用

I maintain a library written in C, which is being accessed by a user on Linux, directly from Python using a module which loads the shared library and call functions. The module is very commonly used, as is this version of the shared library, by people doing a popular tutorial.

用户遇到细分错误.他在gdb下运行他的Python脚本,看到它在共享库中,该函数在为结构分配内存并返回指针的函数中.他正在找回指针,但是当他尝试在随后对共享库的调用中使用它时,由于无法访问内存而发生了分段错误.

The user is getting a segmentation fault. Running his Python script under gdb, he sees that it is in the shared library, within a function that mallocs memory for an struct and returns the pointer. He is getting a pointer back, but when he attempts to use it in subsequent calls to the shared library, the segmentation fault occurs as the memory is inaccessible.

如果他以root身份运行Python脚本,则不会发生此问题.在备用Linux安装中也不会发生.

If he runs the Python script as root, the problem does not occur. Nor does it occur in an alternate Linux installation.

所以回顾一下:

  • 他的Python代码加载了共享库.
  • 然后调用一个函数,该函数返回一个指向共享库中分配的内存的指针.
  • 然后他调用共享库中的另一个函数,并将其返回的指针传递给他,共享库因其自身的指针而阻塞.
  • 仅当他以普通用户在"4.0.7-2-ARCH x86_64 GNU/Linux"上运行它时才会发生.当他切换到root并运行它时,在该OS上不会发生这种情况.
  • 当他尝试在Ubuntu计算机上重现该问题时,不会发生.

有什么作用?这是一些ARCH错误吗?还是对此有一些编程上的细微之处可以解决?

What gives? Is this some ARCH bug? Or is there programming nuances to this which can be cleared up?

您可以在此处阅读详细信息,其中包括足够的详细信息如果问题不是比我多的Linux编程经验的用户不容易理解的问题,请重现该问题.

You can read the minutiae here which includes enough detail to reproduce the problem, if the problem is not self-evident to users with more Linux programming experience than I.

指向共享库功能的快速链接:

Quick links to the shared library functions:

  • Source code for TCOD_map_new.
  • Source code for TCOD_map_set_properties.

为了后代和易于使用而编写的Python代码节选:

Excerpt of his Python code for posterity and ease of access:

#!/usr/bin/env python2
import curses
import libtcodpy as libtcod

def main(stdscr):
    curses.start_color()
    curses.use_default_colors()

    map = libtcod.map_new(10, 10) # any numbers work

    libtcod.map_set_properties(map, 0, 0, True, True) # any in bounds integer coordinates fail
    stdscr.getch()

curses.wrapper(main)

推荐答案

我也遇到了同样的问题.我的解决方案是,我在调用者函数中声明了字符串(malloc()),而不是对被调用者函数的引用进行了传递,并且它填充了内容.

I met the same problem with you. My solution is that I declared the string ( malloc() ) in the caller function, than pass-by-reference to the callee function and it fill the content.

这篇关于为什么共享库中的分配内存无法被应用程序访问?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆