@@ -109,18 +109,22 @@ char *
109
109
npy_string_arena_malloc (npy_string_arena * arena , npy_string_realloc_func r ,
110
110
size_t size )
111
111
{
112
- if ((arena -> size - arena -> cursor ) < size ) {
112
+ // one extra size_t to store the size of the allocation
113
+ size_t string_storage_size = size + sizeof (size_t );
114
+ // expand size to nearest multiple of 8 bytes to ensure 64 bit alignment
115
+ string_storage_size += (8 - string_storage_size % 8 );
116
+ if ((arena -> size - arena -> cursor ) <= string_storage_size ) {
113
117
// realloc the buffer so there is enough room
114
118
// first guess is to double the size of the buffer
115
119
size_t newsize ;
116
120
if (arena -> size == 0 ) {
117
- newsize = size ;
121
+ newsize = string_storage_size ;
118
122
}
119
- else if (((2 * arena -> size ) - arena -> cursor ) > size ) {
123
+ else if (((2 * arena -> size ) - arena -> cursor ) > string_storage_size ) {
120
124
newsize = 2 * arena -> size ;
121
125
}
122
126
else {
123
- newsize = arena -> size + size ;
127
+ newsize = arena -> size + string_storage_size ;
124
128
}
125
129
if ((arena -> cursor + size ) >= newsize ) {
126
130
// doubling the current size isn't enough
@@ -135,8 +139,10 @@ npy_string_arena_malloc(npy_string_arena *arena, npy_string_realloc_func r,
135
139
arena -> buffer = newbuf ;
136
140
arena -> size = newsize ;
137
141
}
138
- char * ret = & arena -> buffer [arena -> cursor ];
139
- arena -> cursor += size ;
142
+ size_t * size_loc = (size_t * )& arena -> buffer [arena -> cursor ];
143
+ * size_loc = size ;
144
+ char * ret = & arena -> buffer [arena -> cursor + sizeof (size_t )];
145
+ arena -> cursor += string_storage_size ;
140
146
return ret ;
141
147
}
142
148
0 commit comments