简体   繁体   中英

Placing floats from string into void array

I get a segmentation fault when my function reads floats from a string and places them in a void array. The segfault occurs after about 200 iterations of the for loop in the following code:

// Allocate memory
void** data;
data = (void**)malloc(num_vals * sizeof(float));

// Convert text to floats
(*(float**)data)[0] = atof(strtok(text, " "));  
for(int index=1; index<num_vals; index++) {
    (*(float**)data)[index] = atof(strtok(NULL, " "));   
    std::cout << (*(float**)data)[index] << std::endl;
}

The void array is necessary because the size and type of data in the string are determined at run-time. I've tried increasing the malloc size, but it doesn't change anything. Any thoughts?

Seriously??

std::vector<float> data;
std::istringstream str(text);
float fv;
while (str >> fv)
{
  data.push_back(fv);
}

Now that's c++

Why do you convert to void ** ??? You code contains couple errors on indexing, so let me show some reasonable changes

float* data;
data = (float*)malloc(num_vals * sizeof(float));

// Convert text to floats
data[0] = atof(strtok(text, " "));  
for(int index=1; index<num_vals; index++) {
 data[index] = atof(strtok(NULL, " "));   
 std::cout << data[index] << std::endl;
}

As much as it pains me to do so, here is a version of your code that probably does what you want.

// Allocate memory
void* data;
data = malloc(num_vals * sizeof(float));

// Convert text to floats
((float*)data)[0] = atof(strtok(text, " "));  
for(int index=1; index<num_vals; index++) {
    ((float*)data)[index] = atof(strtok(NULL, " "));   
    std::cout << ((float*)data)[index] << '\n';
}

Note, however, that if you worked for me and tried to check in that code, we would have a serious discussion about your choice of career.

I'd rather see something like this:

std::vector<float> v;
std::copy(std::istream_iterator<float>(std::istringstream(text)),
          std::istream_iterator<float>(),
          std::back_inserter(v));

Ps Rob's rule #47: Never say std::endl when you mean '\\n' .

我认为,由于您正在定义void指针的指针并将其分配/广播到void指针,因此它为每个元素分配4个字节的内存,因为在C / C ++中,关于指针类型的指针始终为4个字节浮子不够大

You got your types mixed up in your inexplicable attempt to create this monster under the pretence of writing "C++". Anyway. what you're mallocing is nothing but a float* , so you need to cast data back to float* :

((float*)data)[0] = myfloat;

There're several issues. One is - data should be void * , you have redundant * . Other might be alignment, i'm not sure you are able to place a float in any location in the memory.

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