我想知道当使用较小(非零)大小调用realloc时,C或C++标准是否保证指针不会更改:
size_t n=1000;
T*ptr=(T*)malloc(n*sizeof(T));
//<--do something useful (that won't touch/reallocate ptr of course)
size_t n2=100;//or any value in [1,n-1]
T*ptr2=(T*)realloc(ptr,n2*sizeof(T));
//<-- are we guaranteed that ptr2==ptr ?
Run Code Online (Sandbox Code Playgroud)
基本上,操作系统可以自行决定,因为我们释放了大量内存块,他想利用所有realloc来对内存进行碎片整理,并以某种方式移动ptr2?
有没有办法将std :: vector(由T*数据指向)中包含的数据的所有权转移到另一个构造中,防止在向量超出范围后"data"成为悬空指针?
编辑:我不想复制数据(这将是一个简单但无效的解决方案).
具体来说,我希望有类似的东西:
template<typename T>
T* transfer_ownership(vector<T>&v){
T*data=&v[0];
v.clear();
...//<--I'd like to make v's capacity 0 without freeing data
}
int main(){
T*data=NULL;
{
vector<double>v;
...//grow v dynamically
data=transfer_ownership<double>(v);
}
...//do something useful with data (user responsible for freeing it later)
// for example mxSetData(mxArray*A,double*data) from matlab's C interface
}
Run Code Online (Sandbox Code Playgroud)
我想到的唯一可以模仿的是:
{
vector<double>*v=new vector<double>();
//grow *v...
data=(*v)[0];
}
Run Code Online (Sandbox Code Playgroud)
然后,数据将被释放或(在我的情况下)用作mxSetData(mxArray A,双数据).然而,这会导致内存泄漏(用于处理v的容量,大小等的数据结构......但当然不是数据本身).
没有泄漏可能吗?
对于整数类型,是否有等效的 dgemm(来自 BLAS)?我只知道 dgemm、sgemm 用于双精度/单精度矩阵,但希望将它用于整数类型的矩阵,例如 int(或 short int ...)。
注意:我不是在寻找涉及转换为 float/double 的解决方案,而是在寻找快速的库实现。
此外,同样的问题 dgemms(使用 strassen 算法)。