简体   繁体   中英

C program memory violation dependant on std::cout (?)

I've written an extension in C++ for Python, and I'm currently debugging it. The extension takes 3 numpy matrices and produces 2 as a result. To the inner C++ function that does the actualy calculation I pass 3 float C arrays (just flattened and converted from input numpy arrays), and return a C float array of arrays. Everything works as intended but ONLY if I print this output array of arrays before returning it.

What the hell is going on in here?

float** gradient(float* inputs, float* kernels, float* grads, npy_intp* input_dims, npy_intp* kernels_dims, npy_intp* output_dims){


float* g_inputs = new float[batch*h*w*ch_in];
for (int i = 0; i < batch*h*w*ch_in; i++) g_inputs[i] = 0;
float* g_kernels = new float[size*ch_out];
for (int i = 0; i < size*ch_out; i++) g_kernels[i] = 0;


float* ret[2] = {{g_inputs}, {g_kernels}};
std::cout<<ret<<std::endl; //<---without this it doesn't work
return ret;
}

I've omitted irrelevant code for clarity.

You are returning a pointer to an object with automatic lifetime. In other words, your function returns a dangling pointer, which is Undefined Behaviour.

Although aerostatic lizards are an uncommon result of UB, anything can happen and the symptom you observe, unlike the lizards, is common.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM