如何为char ** str添加空值

时间:2016-01-13 10:36:28

标签: c pointers dynamic-memory-allocation realloc off-by-one

我怎样才能为char ** str设置一个空值,因为即时通讯有“错误”和“使用C语言排除超出绑定指针的引用:1个字节(1个元素)到数组的结尾”

while(part)
    {
        res = (char**)realloc(res, (i + 1) * sizeof(char*));
        *(res + i) = mystrdup(part);

        part = mystrdup(strtok(NULL, delim));
        i++;
    }
    res = (char**)realloc(res, i * sizeof(char*));
    *(res + i) = NULL; // This is where I Encounter the ERROR

1 个答案:

答案 0 :(得分:2)

在这段代码中

res = (char**)realloc(res, i * sizeof(char*));
*(res + i) = NULL;

尝试访问*(res + i),您将前往off-by-one。你应该写

*(res + i -1) = NULL;

话虽如此,

  • Please see this discussion on why not to cast the return value of malloc() and family in C.
  • pointerP = realloc (pointerP, .....)这样的语句被认为是非常不安全的,例如,如果realloc()失败,你最终也会失去实际的指针。
  • 始终针对malloc()检查NULL和一系列功能的返回值,以确保成功。
  • 此外,在将strtok()传递给strdup()之前,对<?php $json = '{ "customer_id": "1", "products":[ { "product_id": "1", "product_qty": "2" }, { "product_id": "2", "product_qty": "4" }, { "product_id": "3", "product_qty": "12" }, { "product_id": "4", "product_qty": "22" }], "order_totalamount": "100" }'; $obj = json_decode($json); $data=$obj->{'products'}; foreach($data as $item){ $sql = "insert into `order`(cm_id,product_id,product_quantity,order_totalamount,order_id,order_date) values ($cus_id,".$item->{'product_id'}.",".$item->{'product_qty'}.",$order_totalamount,$cus_id,CURDATE())"; } ?>的返回值进行NULL检查。
相关问题