Skip to content

unsafeNew(UncheckedArrayXxx) does not calculate the size of sizeof(dummy). #22556

@haoyu234

Description

@haoyu234

Description

I allocated 10 bytes of memory, one byte occupied by the dummy field.

type
  ChunkObj = object
    data: UncheckedArray[byte]

proc alloc(size: int): ref ChunkObj =
  unsafeNew(result, size)

proc main() =
  let buf = alloc(10)
  buf.data[9] = 100    # index out of bounds, because one byte is occupied by the 'dummy' field, 
                       # the actual usable size of data is 9 bytes
struct tyObject_ChunkObj__mOTFrUaGXmv4xFi10w76AA {
	char dummy;                                     // one byte
	NU8 data[SEQ_DECL_SIZE];
};

Here is the C code for the alloc function:

N_LIB_PRIVATE N_NIMCALL(tyObject_ChunkObj__mOTFrUaGXmv4xFi10w76AA*, alloc__spaces_u3)(NI size_p0) {
	tyObject_ChunkObj__mOTFrUaGXmv4xFi10w76AA* result;
	nimfr_("alloc", "/root/repos/spaces/src/spaces.nim");
{	result = NIM_NIL;
	nimln_(11);	eqdestroy___spaces_u32(result);
	if ((size_p0) < ((NI)0) || (size_p0) > ((NI)IL64(9223372036854775807))){ raiseRangeErrorI(size_p0, ((NI)0), ((NI)IL64(9223372036854775807))); goto BeforeRet_;
	}
	result = (tyObject_ChunkObj__mOTFrUaGXmv4xFi10w76AA*) nimNewObj(((NI) (size_p0)), NIM_ALIGNOF(tyObject_ChunkObj__mOTFrUaGXmv4xFi10w76AA));
	}BeforeRet_: ;
	popFrame();
	return result;
}

size_p0 is the size of memory I want to allocate, which is 10, and the value of sizeof(dummy) should be added when calling the 'nimNewObj' function.

Nim Version

Nim Compiler Version 2.1.1 [Linux: amd64]
Compiled at 2023-08-23
Copyright (c) 2006-2023 by Andreas Rumpf

git hash: 6b04d03
active boot switches: -d:release

Current Output

no output, no exception

Expected Output

no output, no exception

Possible Solution

Add the value of sizeof(dummy) before calling the unsafeNew function.
For compatibility reasons, I used offsetof(ChunkObj, data), but offsetof(ChunkObj, data) didn't work, see #22553

Additional Information

No response

Metadata

Metadata

Assignees

Type

No type

Projects

No projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions