Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C program keeps crashing when calling perl function newSVpv()

Tags:

c

perl

xs

Trying to use perl data structure (partially as a way to support associative array in C), but the following program keep crashing. It compiles fine but will crash on the line with newSVpv(). Not sure why.

#include <EXTERN.h>               /* from the Perl distribution     */
#include <perl.h>                 /* from the Perl distribution     */
static PerlInterpreter *my_perl;  /***    The Perl interpreter    ***/
int main(int argc, char **argv, char **env) {
    char *proto = "http";
    SV* ret = newSVpv("http", 4);
    sv_catpvn(ret, "://", 3);
    STRLEN len = 1;
    char *result = SvPV(ret, len);
    printf("result: %p %d\n", result, len);
    return 0;
}

The line to compile it is

gcc -g -o interp te1.c `perl -MExtUtils::Embed -e ccopts -e ldopts`

The perl I have is 5.14.2 running on Ubuntu 12.04.4 LTS.

Thanks for any tips!

UPDATE: Added the gdb trace. Thanks for asking. gdb trace:

Program received signal SIGSEGV, Segmentation fault.
0x00007ffff7b235a6 in Perl_newSVpv () from /usr/lib/libperl.so.5.14
(gdb) bt
#0  0x00007ffff7b235a6 in Perl_newSVpv () from /usr/lib/libperl.so.5.14
#1  0x0000000000400927 in main (argc=1, argv=0x7fffffffe1e8, 
    env=0x7fffffffe1f8) at te1.c:7
(gdb) 
like image 607
packetie Avatar asked Mar 17 '23 00:03

packetie


1 Answers

I'm usually calling C from Perl, rather than Perl from C, but I'm pretty sure that your problem is that you haven't copied the PERL_SYS_INIT3, perl_alloc, and perl_construct bits from the perlembed example and so you don't actually have a perl interpreter structure to work with. newSVpv is bombing out when it tries to access something through the nonexistent interpreter pointer.

The last three lines of that example (perl_destruct, perl_free, and PERL_SYS_TERM) should also be called at the end of your program as a matter of good practice.

like image 174
hobbs Avatar answered Apr 26 '23 07:04

hobbs