标签: unsafe

直接从数组创建字符串不安全

目前我知道的将字符串的第一个字母大写的最快方法如下:

var array = str.ToCharArray();
array[0] = char.ToUpper(array[0]);
return new string(array);
Run Code Online (Sandbox Code Playgroud)

这涉及 2 个数组分配:char.ToUpper(array[0])以及复制到new string(array).

因为我知道array不能逃避这个方法,有没有办法使用不安全的代码来避免第二次分配?

c# unsafe

1
推荐指数
1
解决办法
241
查看次数

为什么不将 u8 指针转换为 [bool; 8] 指针逐位产生数字?

我正在 Rust 中尝试原始指针。我有以下代码:

fn main() {
    let mut t: u8 = 0;

    let addr = &mut t as *mut u8 as usize;

    let x = addr as *mut [bool; 8];

    let y = addr as *mut u8;
    unsafe {
        *y = 0b10101010;
        println!("{:?} {:b}", *x, *y);
    }
}
Run Code Online (Sandbox Code Playgroud)

它产生以下输出:[true, true, true, true, true, true, true, false] 10101010 虽然我希望它打印[true, false, true, false, true, false, true, false] 10101010. 到底是怎么回事?bool数组不是按位存储的吗?

unsafe rust

1
推荐指数
1
解决办法
909
查看次数

对于可变索引锈蚀,是否有替代这种不安全代码的方法

我正在制作一个国际象棋游戏,当数组的索引(aVec2超出范围)时,我希望从棋子数组中返回一个可变的空字符,我需要这样做的原因是我的函数用于移动棋子片段需要对索引片段的可变引用,长话短说,我最终需要创建一个NULL_PIECE可以在函数中引用的静态变量,但这可能非常危险,正如您从我的代码中看到的那样

impl Index<IVec2> for Board {
    type Output = Piece;
    fn index(&self, index : IVec2) -> &Self::Output{
        if (index.abs() != index) || (index.max_element() > WIDTH-1) {
            &Piece('\0') // this works
        } else {
            let i : usize = (index.x + WIDTH* index.y).try_into().unwrap();
            &self.pieces[i]
        }
    }
}

impl IndexMut<IVec2> for Board {
    fn index_mut(&mut self, index: IVec2) -> &mut Self::Output{
        if (index.abs() != index) || (index.max_element() > WIDTH-1) {
            // &mut Piece('\0')  // this does not work …
Run Code Online (Sandbox Code Playgroud)

indexing static unsafe rust

1
推荐指数
1
解决办法
106
查看次数

为什么“mem::forget”盒子被认为是安全的?

以下代码创建框,每个框都指向 4096 字节的块。如果我在发布时运行它,一切都会被优化掉:(,但在调试时,这会按预期运行并泄漏大量内存......或者是吗?

fn main() {
    for _ in 0..1000 {
        for _ in 0..100000 {
            let b = Box::new([!0u64; 1 << 10]);
            std::mem::forget(b);
        }
        let mut buf = String::new();
        let _ = std::io::stdin().read_line(&mut buf);
    }
}
Run Code Online (Sandbox Code Playgroud)

为什么这不被认为是不安全的?

unsafe rust

1
推荐指数
2
解决办法
577
查看次数

设计样条函子的更合理方法?

我对样条数据结构做了以下定义:

#[derive(Clone, Debug)]
pub struct BSpline
{
    knots: Vec<f32>,
    control_points: Vec<Vec3>,
    /// Internal helper variable. Used to optimize repetetitive samplings on close
    /// $t$ values.
    last_t_index: usize,
    order: usize,
}

impl BSpline
{
    pub fn sample(&self, t: f32) -> Vec3
    {
        debug_assert!(self.control_points.len() >= self.order);

        let t = f32::clamp(t, self.knots[0], *self.knots.last().unwrap());

        let mut t_index = self.last_t_index;
        while !(t >= self.knots[t_index] && t <= self.knots[t_index + 1])
        {
            t_index = (t_index + 1) % self.knots.len();
        }

        // TODO(low): find a better way …
Run Code Online (Sandbox Code Playgroud)

pointers unsafe type-safety rust

1
推荐指数
1
解决办法
60
查看次数

这个功能可以更安全吗?寻找提示和你的想法!

这有点奇怪的问题.

我写了一个C函数.它的'喜欢'strchr/strrchr.它应该在c字符串中查找一个字符,但是向后移动,并返回指向它的指针.由于c字符串不是"空启动",它还需要第三个参数'count',表示它应该向后看的字符数.

/*
*s: Position from where to start looking for the desired character.
*c: Character to look for.
*count: Amount of tests to be done
*
* Returns NULL if c is not in (s-count,s)
* Returns a pointer to the occurrence of c in s.
*/
char* b_strchr(const char* s,int c,size_t count){

    while (count-->0){

        if (*s==c) return s;
        s--;
     }
     return NULL;
}
Run Code Online (Sandbox Code Playgroud)

我已经对它进行了一些测试,但是你看到它有什么缺陷吗?安全问题左右?任何增强功能?可以改进吗?更重要的是:这是一个坏主意吗?

一些用法.

    char* string = "1234567890";

    printf("c: %c\n",*b_strchr(string+9,'5',10));//prints 5

    printf("c: %c\n",*b_strchr(string+6,'1',7));//prints 1
Run Code Online (Sandbox Code Playgroud)

编辑:新界面,一些变化. …

c unsafe

0
推荐指数
1
解决办法
249
查看次数

C#中的结构泛型

请帮我解决这个问题:

我尝试定义这样的结构:

 unsafe struct sNodo<T>
{    
        public T info;
        public sNodo<T>* sIzq;}
Run Code Online (Sandbox Code Playgroud)

但我收到此错误:无法获取地址,获取大小,或声明指向托管类型sNodo的指针,

我该怎么解决?我正在尝试使用动态内存创建一个"通用"堆栈.

感谢您的关注

c# struct unsafe

0
推荐指数
1
解决办法
1771
查看次数

从byte []到byte*的更好方法

有没有更好的办法?请注意,我没有使用,fixed因为我需要扫描缓冲区数据.

GCHandle pinned1 = GCHandle.Alloc(Pic1, GCHandleType.Pinned);
IntPtr ptr1 = pinned1.AddrOfPinnedObject();
byte* p1 = (byte*)ptr1.ToPointer();
//...
//...
//...
byte a=*p1;
p1++;
//...
//...
pinned1.Free();
Run Code Online (Sandbox Code Playgroud)

.net c# optimization unsafe

0
推荐指数
1
解决办法
162
查看次数

在C#中,有没有办法模拟传递指针(不使用unsafe关键字)

如果不使用'Unsafe'关键字,可以完成以下操作:

将字段作为参数传递给函数.该函数可以定期更改该字段的值.

所以,如果我有:

int MyField;
Run Code Online (Sandbox Code Playgroud)

和:

MyFunction(ref MyField)
Run Code Online (Sandbox Code Playgroud)

该函数可以存储指针MyField并根据需要更改其值.

在C++中,我们只是传递一个指向该值的指针,然后根据需要进行更改,但我试图找出是否可以在C#中完成.我猜它可以通过反思来完成.

c# pointers unsafe

0
推荐指数
2
解决办法
1177
查看次数

不安全代码块后变量丢失

我有一个非常奇怪的问题.这是我的代码:

<declare E,JV>

<perform some actions with E>
JV.Math_Mul(E);
Run Code Online (Sandbox Code Playgroud)

////

public new void Math_Mul(Matrix a)
    {

        double[,] vC = new double[a.ColCount, this.RowCount];


        externExtensions.MatMul(vC,a.Values ,this.Values, a.RowCount, this.ColCount, a.ColCount);
        Values = vC;

        CopyB(B.Values,vC);
     }

    static unsafe void CopyB(double[,] B, double[,] val)
    {
        int Col = val.GetLength(1);
        int j = 0;
        fixed (double* pA = B, pB = val)
        {
            for (int i = 0; i < val.Length; i++)
            {
                if (i != j * Col)
                    pA[i-j] = pB[i];
                else
                    j++;

            }
        } …
Run Code Online (Sandbox Code Playgroud)

c# pointers unsafe

0
推荐指数
1
解决办法
189
查看次数

标签 统计

unsafe ×10

c# ×5

rust ×4

pointers ×3

.net ×1

c ×1

indexing ×1

optimization ×1

static ×1

struct ×1

type-safety ×1