0

My function purpose is to make custom sized array and pass it to python. Problem is everytime I try to do so, I get

Error in `python3': double free or corruption (fasttop)

or something similar.

I have produced a minimal example of such bug (I built tst.so shared library):

for c++:

int * lala = new int[1];
void def()
{
    delete[] lala;
    int * lala = new int[100];
}
extern "C" int * abc()
{
    def();
    return lala;
}

for python:

import ctypes
import numpy as np
from numpy.ctypeslib import ndpointer
import inspect
from os.path import abspath, dirname, join
fname = abspath(inspect.getfile(inspect.currentframe()))
libIII = ctypes.cdll.LoadLibrary(join(dirname(fname), 'tst.so'))
abc = libIII.abc
abc.restype = ndpointer(dtype=ctypes.c_int, shape=(100,))
abc.argtypes= None
asd = np.reshape(np.frombuffer(abc(), dtype = np.uint16), (100))
asd = np.reshape(np.frombuffer(abc(), dtype = np.uint16), (100))
asd = np.reshape(np.frombuffer(abc(), dtype = np.uint16), (100))

if I make int * lala = new int[100]; (same size as it should be), everything works. Am I doing something wrong? How should I delete old array and make other with different size?

1 Answer 1

1

You are declaring a local lala inside def. Allocating memory for that will not change the global lala. Instead, do this:

void def()
{
    delete[] lala;
    lala = new int[100];   // use global lala
}  
Sign up to request clarification or add additional context in comments.

1 Comment

No worries, happens to all of us. Learn how to use a debugger, it'll help you catch these bugs yourself.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.