import std.stdio;

void foo(char* ptr) { if (判断ptr指向的内存区域是否可写) { writeln('error: ptr points to read-only data'); return; }

// do something with ptr
ptr[0] = 'H';

}

void main() { const char* allStr = 'hello world'; foo(cast(char*)allStr); }

foo函数我应该怎么判断ptr指向的数据是否可写,防止段地址错误,我百分百确认core.memory.isWritable和core.stdc.string.mem_is_writable和core.memory.GC.isWritable已经在最新版本dmd中失效过期了,换句话说怎么判断char*不是指向文字常量区的数据内容:可以使用core.memory.isInHeap函数来判断指针是否指向堆内存区域,然后再使用core.memory.isWritable函数判断该内存区域是否可写。代码如下:

import core.memory; import std.stdio;

void foo(char* ptr) { if (!isInHeap(ptr) || !isWritable(ptr)) { writeln('error: ptr points to read-only data'); return; }

// do something with ptr
ptr[0] = 'H';

}

void main() { const char* allStr = 'hello world'; foo(cast(char*)allStr); }

这样就可以避免指针指向文字常量区的问题。

D 语言如何判断指针指向的内存区域是否可写

原文地址: https://www.cveoy.top/t/topic/joep 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录