Skip to content

Commit fef4d19

Browse files
committed
Fix memory corruption with NSMutableData(length:)
addition of testcase
1 parent 73218c8 commit fef4d19

File tree

2 files changed

+10
-5
lines changed

2 files changed

+10
-5
lines changed

Foundation/NSData.swift

Lines changed: 2 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -936,9 +936,7 @@ extension NSMutableData {
936936
}
937937

938938
public convenience init?(length: Int) {
939-
let memory = malloc(length)
940-
self.init(bytes: memory, length: length, copy: false) { buffer, amount in
941-
free(buffer)
942-
}
939+
self.init(bytes: nil, length: 0)
940+
self.length = length
943941
}
944942
}

TestFoundation/TestNSData.swift

Lines changed: 8 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -39,7 +39,8 @@ class TestNSData: XCTestCase {
3939
("test_initializeWithBase64EncodedStringGetsDecodedData", test_initializeWithBase64EncodedStringGetsDecodedData),
4040
("test_base64DecodeWithPadding1", test_base64DecodeWithPadding1),
4141
("test_base64DecodeWithPadding2", test_base64DecodeWithPadding2),
42-
("test_rangeOfData",test_rangeOfData)
42+
("test_rangeOfData",test_rangeOfData),
43+
("test_initMutableDataWithLength", test_initMutableDataWithLength)
4344
]
4445
}
4546

@@ -338,4 +339,10 @@ class TestNSData: XCTestCase {
338339

339340
}
340341

342+
func test_initMutableDataWithLength() {
343+
let mData = NSMutableData(length: 30)
344+
XCTAssertNotNil(mData)
345+
XCTAssertEqual(mData!.length, 30)
346+
}
347+
341348
}

0 commit comments

Comments
 (0)