@@ -193,7 +193,7 @@ void sdsclear(sds s) {
193193 *
194194 * Note: this does not change the *length* of the sds string as returned
195195 * by sdslen(), but only the free buffer space we have. */
196- sds sdsMakeRoomFor (sds s , size_t addlen ) {
196+ sds sdsMakeRoomFor (sds s , size_t addlen ) {
197197 void * sh , * newsh ;
198198 size_t avail = sdsavail (s );
199199 size_t len , newlen ;
@@ -204,8 +204,12 @@ sds sdsMakeRoomFor(sds s, size_t addlen) {
204204 if (avail >= addlen ) return s ;
205205
206206 len = sdslen (s );
207- sh = (char * )s - sdsHdrSize (oldtype );
208- newlen = (len + addlen );
207+ sh = (char * )s - sdsHdrSize (oldtype );
208+
209+ /* Fix: Prevent Integer Overflow */
210+ if (addlen > SIZE_MAX - len ) return NULL ; /* Prevent overflow */
211+ newlen = len + addlen ;
212+
209213 if (newlen < SDS_MAX_PREALLOC )
210214 newlen *= 2 ;
211215 else
@@ -219,25 +223,34 @@ sds sdsMakeRoomFor(sds s, size_t addlen) {
219223 if (type == SDS_TYPE_5 ) type = SDS_TYPE_8 ;
220224
221225 hdrlen = sdsHdrSize (type );
222- if (oldtype == type ) {
223- newsh = s_realloc (sh , hdrlen + newlen + 1 );
226+
227+ /* Fix: Ensure safe memory allocation */
228+ if (hdrlen + newlen + 1 < newlen ) return NULL ; /* Prevent overflow */
229+
230+ if (oldtype == type ) {
231+ newsh = s_realloc (sh , hdrlen + newlen + 1 );
224232 if (newsh == NULL ) return NULL ;
225- s = (char * )newsh + hdrlen ;
233+ s = (char * )newsh + hdrlen ;
226234 } else {
227235 /* Since the header size changes, need to move the string forward,
228236 * and can't use realloc */
229- newsh = s_malloc (hdrlen + newlen + 1 );
237+ newsh = s_malloc (hdrlen + newlen + 1 );
230238 if (newsh == NULL ) return NULL ;
231- memcpy ((char * )newsh + hdrlen , s , len + 1 );
239+ memcpy ((char * )newsh + hdrlen , s , len + 1 );
232240 s_free (sh );
233- s = (char * )newsh + hdrlen ;
241+ s = (char * )newsh + hdrlen ;
234242 s [-1 ] = type ;
235243 sdssetlen (s , len );
236244 }
245+
246+ /* Fix: Prevent setting a too-large allocation */
247+ if (newlen > sdsTypeMaxSize (type )) newlen = sdsTypeMaxSize (type );
237248 sdssetalloc (s , newlen );
249+
238250 return s ;
239251}
240252
253+
241254/* Reallocate the sds string so that it has no free space at the end. The
242255 * contained string remains not altered, but next concatenation operations
243256 * will require a reallocation.
0 commit comments