首页 > 其他 > 详细

LeetCode: fault list

时间:2018-06-02 10:46:54      阅读:222      评论:0      收藏:0      [点我收藏+]

1. malloc memory should always use the following form:

int *a = malloc(sizeof(int) * 3);
int **b = malloc(sizeof(int*) * 3);
int i = 0;
for (; i < 3; i++) {
    b[i] = malloc(sizeof(int) * 3);
}
char *c = malloc(sizeof(char) * length);
char **pc = malloc(sizeof(char *) * 4);
for (i = 0; i < 4; i++) {
    pc[i] = malloc(sizeof(char) * 3);
}

2. memset memory to 0 should use the form:

// Using the malloced memory above:
memset(a, 0, sizeof(int) * 3);
memset(b, 0, sizeof(int*) * 3);
for (i = 0; i < 3; i++) {
    memset(b[i], 0, sizeof(int) * 3);
}
memset(c, 0, sizeof(char) * 3);
memset(pc, 0, sizeof(char *) * 4);
for (i = 0; i < 4; i++) {
    memset(pc[i], 0, sizeof(char) * 3);
}

3. malloc(0) might also return address which is non-null. Which is error-prone. Consider use the following malloc. (..my implementation, any suggestion?)

#define SMALLOC(x)       \
({                                   void *addr;                       if ((x) == 0)                   addr = 0;                       else addr = malloc(x);     (addr);                           })

 

LeetCode: fault list

原文:https://www.cnblogs.com/sansna/p/9124282.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!