Skip to content

Commit edb0920

Browse files
committed
Fix behavior strndup whern size <= 0, in this case strndup returns empty string
1 parent b4bfabd commit edb0920

File tree

2 files changed

+20
-8
lines changed

2 files changed

+20
-8
lines changed

src/library.js

Lines changed: 6 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -4203,8 +4203,12 @@ LibraryManager.library = {
42034203
strndup: function(ptr, size) {
42044204
var len = String_len(ptr);
42054205

4206-
if (size <= 0 || size >= len) {
4207-
return _strdup(ptr);
4206+
if (size >= len) {
4207+
return _strdup(ptr);
4208+
}
4209+
4210+
if (size < 0) {
4211+
size = 0;
42084212
}
42094213

42104214
var newStr = _malloc(size + 1);

tests/runner.py

Lines changed: 14 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -1406,26 +1406,34 @@ def test_strndup(self):
14061406
int main(int argc, char **argv) {
14071407
const char* source = "strndup - duplicate a specific number of bytes from a string";
14081408
1409-
char* strdup_val = strndup(source, 7);
1410-
printf("%s\\n", strdup_val);
1409+
char* strdup_val = strndup(source, 0);
1410+
printf("1:%s\\n", strdup_val);
1411+
free(strdup_val);
1412+
1413+
strdup_val = strndup(source, 7);
1414+
printf("2:%s\\n", strdup_val);
14111415
free(strdup_val);
14121416
14131417
strdup_val = strndup(source, 1000);
1414-
printf("%s\\n", strdup_val);
1418+
printf("3:%s\\n", strdup_val);
14151419
free(strdup_val);
14161420
14171421
strdup_val = strndup(source, 60);
1418-
printf("%s\\n", strdup_val);
1422+
printf("4:%s\\n", strdup_val);
14191423
free(strdup_val);
14201424
14211425
strdup_val = strndup(source, 19);
1422-
printf("%s\\n", strdup_val);
1426+
printf("5:%s\\n", strdup_val);
1427+
free(strdup_val);
1428+
1429+
strdup_val = strndup(source, -1);
1430+
printf("6:%s\\n", strdup_val);
14231431
free(strdup_val);
14241432
14251433
return 0;
14261434
}
14271435
'''
1428-
self.do_run(src, 'strndup\nstrndup - duplicate a specific number of bytes from a string\nstrndup - duplicate a specific number of bytes from a string\nstrndup - duplicate\n')
1436+
self.do_run(src, '1:\n2:strndup\n3:strndup - duplicate a specific number of bytes from a string\n4:strndup - duplicate a specific number of bytes from a string\n5:strndup - duplicate\n6:\n')
14291437

14301438
def test_errar(self):
14311439
src = r'''

0 commit comments

Comments
 (0)