• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  * Copyright (C) 2022 Huawei Device Co., Ltd.
3  * Licensed under the Apache License, Version 2.0 (the "License");
4  * you may not use this file except in compliance with the License.
5  * You may obtain a copy of the License at
6  *
7  *     http://www.apache.org/licenses/LICENSE-2.0
8  *
9  * Unless required by applicable law or agreed to in writing, software
10  * distributed under the License is distributed on an "AS IS" BASIS,
11  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12  * See the License for the specific language governing permissions and
13  * limitations under the License.
14  */
15 
16 #include <malloc.h>
17 #include <errno.h>
18 #include <string.h>
19 #include "test.h"
20 
main(int argc,char * argv[])21 int main(int argc, char *argv[])
22 {
23 	uintptr_t *c0 = (uintptr_t *)malloc(sizeof(uintptr_t) * 10);
24 	if (!c0) {
25 		t_error("Malloc c0 failed: %s\n", strerror(errno));
26 		return -1;
27 	}
28 	/* Malloc dividing chunk to avoid combination of neighbouring freed chunk */
29 	void *d0 = malloc(sizeof(uintptr_t) * 10);
30 	if (!d0) {
31 		t_error("Malloc d0 failed: %s\n", strerror(errno));
32 		return -1;
33 	}
34 
35 	uintptr_t *c1 = (uintptr_t *)malloc(sizeof(uintptr_t) * 10);
36 	if (!c1) {
37 		t_error("Malloc c1 failed: %s\n", strerror(errno));
38 		return -1;
39 	}
40 	/* Malloc dividing chunk to avoid combination of neighbouring freed chunk */
41 	void *d1 = malloc(sizeof(uintptr_t) * 10);
42 	if (!d1) {
43 		t_error("Malloc d1 failed: %s\n", strerror(errno));
44 		return -1;
45 	}
46 
47 	/* Free the chunk, with same size, they're put into the same bin */
48 	/*    --------      --------      --------
49 	 *    |  c0  |      |  c1  |      |  bin |
50 	 * -->| next |----->| next |----->| next |-----
51 	 * |  | prev |<-----| prev |<-----| prev |    |
52 	 * |  -------       -------       -------     |
53 	 * --------------------------------------------
54 	 */
55 	free(c0);
56 	free(c1);
57 
58 	uintptr_t xoraddr = c0[0]; /* Get the next of c0 */
59 	uintptr_t realaddr = (uintptr_t)((char *)c1 - sizeof(uintptr_t) * 2);
60 	if (xoraddr == realaddr) {
61 		t_error("encoding pointer is equal to real pointer\n");
62 	}
63 
64 	free(d0);
65 	free(d1);
66 
67 	return t_status;
68 }
69