问题
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.
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.
If he runs the Python script as root, the problem does not occur. Nor does it occur in an alternate Linux installation.
So to recap:
- His Python code loads the shared library.
- It then calls a function which returns a pointer to memory allocated within the shared library.
- Then he calls another function in the shared library, and passed in the pointer it returned to him, and the shared library chokes on it's own pointer.
- It only occurs when he runs it as a normal user on "4.0.7-2-ARCH x86_64 GNU/Linux". It does not occur on that OS, when he switches to root and runs it.
- It does not occur when he attempts to reproduce the problem on a Ubuntu machine.
What gives? Is this some ARCH bug? Or is there programming nuances to this which can be cleared up?
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.
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)
回答1:
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.
来源:https://stackoverflow.com/questions/31375177/why-might-mallocd-memory-from-a-shared-library-be-inaccessible-to-the-applicati