MacOS C行为不一致

安东·斯塔菲耶夫(Anton Stafeyev)

我在MacOS上发生了一件很奇怪的事情,我正在研究一个简单的非动态矢量结构,每当尝试打印它时,都会得到非常错误的结果。我确实在Linux机器上运行了相同的东西,而我的问题是零

#include "Vector.h"
#include <stdlib.h>

#define VECTOR_SIZE 4

typedef struct _dVec{
    uint32_t len;
    float *_val;
}_dVec;

//Create vector mem
Vector vecinit(int lenght){
    
    //Allocate and init vector
    Vector _vec = malloc(VECTOR_SIZE + sizeof(float) * lenght);
    _vec->len = lenght;
    _vec->_val = (float *) _vec + 4;
    
    return _vec;
}


//Insert a index
void vec_inat(Vector vector, int index, float value){
    vector->_val[index] = value;
}

//Return  from index
float vec_outat(Vector vector, int index){
    return vector->_val[index];
}

int veclen(Vector vector){
    return vector->len;
}

float *vecptr(Vector vector){
    return vector->_val;
}

void vecdeinit(Vector vector){
    if(vector){
        free(vector);
    }
}

向量

#ifndef Vector_h
#define Vector_h

typedef struct _dVec *Vector;


//Create vector mem
Vector vecinit(int length);

//Insert a index
void vec_inat(Vector vector, int index, float value);

//Return  from index
float vec_outat(Vector vector, int index);

//Vector Length
int veclen(Vector vector);

//Pointer to data
float *vecptr(Vector vector);

//deinit
void vecdeinit(Vector vector);

#endif /* Vector_h */

如您所见,预期的输出是

0.300000
0.600000
0.600000
0.600000
0.600000
0.600000
0.600000
0.600000
0.600000
0.200000
Program ended with exit code: 0

但是我得到了这个

0.300000
0.600000
0.600000
0.600000
0.600000
0.600000
0.600000
0.600000
0.000000
0.000000

奇怪的是:

1) If I set a breakpoint on the first loop and slowly iterate the desired result is achieved

2) If I set length of a vector higher, I get a desired result

我不知道发生了什么。我在macOS Catalina上运行它。

main.c

int main(int argc, const char * argv[]) {
    Vector vec = vecinit(10);
    
    for(int i = 0; i < veclen(vec); i++){
        vec_inat(vec, i, 0.6f);
    }
    
    vec_inat(vec, 0, 0.3f);
    vec_inat(vec, 9, 0.2f);
    
    
    for(int i = 0; i < veclen(vec); i++){
        printf("%f\n", vec_outat(vec, i));
    }
    
    vecdeinit(vec);
    
    return 0;
}
卡尔·诺鲁姆

您的代码似乎是实现灵活数组成员的困难/错误方式。只需正确使用一个,就像这样:

typedef struct _dVec{
    uint32_t len;
    float _val[];
}_dVec;

//Create vector mem
Vector vecinit(int lenght){
    
    //Allocate and init vector
    Vector _vec = malloc(sizeof(_dVec) + lenght * sizeof(float));
    _vec->len = lenght;
    
    return _vec;
}

应该解决您所有的问题。如果您真的很想这么做,那就修正分配:

Vector _vec = malloc(sizeof(_dVec) + sizeof(float) * lenght);

和你的指针算法:

_vec->_val = (float *)(_vec + 1);

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章