wutzebaer wutzebaer -3 years ago 165
C++ Question

Segmentation fault when deleting a Array

I have simplified the following functions, when trying to delete the array after using it i get a segfault.

float * MyService::innerFunction(MyClass& feature) {
float* target = new float[1];
target[0] = feature.getValue();
target[1] = 1;
return target;

float MyService::outerFunction(MyClass& feature){
float* input = innerFunction(feature);
delete[] input; <- seg fault
return result;

Answer Source

Your array is too small. float* target = new float[1]; allocates only one element but you assign two. target[1] = 1; corrupts your head.

So you need to to do:

float* target = new float[2];
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download