Skip to content
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.

Commit e1dacbd

Browse files
committedMar 13, 2025·
fix memory leak issue and finish most functions
Signed-off-by: hwware <[email protected]>
1 parent 3e957b1 commit e1dacbd

File tree

1 file changed

+17
-5
lines changed

1 file changed

+17
-5
lines changed
 

‎src/db.c

+17-5
Original file line numberDiff line numberDiff line change
@@ -875,13 +875,16 @@ void randomWithCountCommand(client *c) {
875875
long l;
876876
unsigned long count;
877877
unsigned long numkeys = 0;
878+
int canDuplicated = 0;
879+
dict *section_dict;
878880

879881
if (getRangeLongFromObjectOrReply(c, c->argv[2], -LONG_MAX, LONG_MAX, &l, NULL) != C_OK) return;
880882
if (l >= 0) {
881883
count = (unsigned long)l;
882884
} else {
883885
/* A negative count means: return the same elements multiple times */
884886
count = -l;
887+
canDuplicated = 1;
885888
}
886889

887890
/* If count is zero, serve it ASAP to avoid special cases later. */
@@ -890,11 +893,13 @@ void randomWithCountCommand(client *c) {
890893
return;
891894
}
892895

893-
int maxtries = 100 * count;
896+
if (canDuplicated) {
897+
section_dict = dictCreate(&stringSetDictType);
898+
dictExpand(section_dict, count);
899+
}
894900

901+
int maxtries = 100 * count;
895902
void *replylen = addReplyDeferredLen(c);
896-
dict *section_dict = dictCreate(&stringSetDictType);
897-
dictExpand(section_dict, 100);
898903
while (maxtries-- > 0 && count > 0) {
899904
void *entry;
900905
int randomDictIndex = kvstoreGetFairRandomHashtableIndex(c->db->keys);
@@ -904,14 +909,21 @@ void randomWithCountCommand(client *c) {
904909
}
905910
robj *valkey = entry;
906911
sds key = objectGetKey(valkey);
907-
if (dictAdd(section_dict, key, NULL) != DICT_OK) {
908-
continue;
912+
if (canDuplicated) {
913+
sds dictKey = sdsdup(key);
914+
if (dictAdd(section_dict, dictKey, NULL) != DICT_OK) {
915+
sdsfree(dictKey);
916+
continue;
917+
}
909918
}
910919
addReplyBulkCBuffer(c, key, sdslen(key));
911920
numkeys++;
912921
count--;
913922
}
914923
setDeferredArrayLen(c, replylen, numkeys);
924+
if (canDuplicated) {
925+
dictRelease(section_dict);
926+
}
915927
}
916928

917929
/************************************************************

0 commit comments

Comments
 (0)
Please sign in to comment.