0

How can I put a null value for char** str because im having and Error of "Dereference of out of bound pointer: 1 bytes(1element) past end of array im using C language"

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
Sourav Ghosh
  • 133,132
  • 16
  • 183
  • 261
  • 3
    [Please see this discussion on why not to cast the return value of `malloc()` and family in `C`.](http://stackoverflow.com/q/605845/2173917). – Sourav Ghosh Jan 13 '16 at 10:37
  • Does your question concern C++? How? – eerorika Jan 13 '16 at 10:38
  • 1
    Isn't it like after the `realloc()`, `*(res + i) = NULL;` should be `*(res + i -1) = NULL;` or am I missing something? – Sourav Ghosh Jan 13 '16 at 10:40
  • What do you mean with "null value"? The value `0x0`? A _null pointer_? – too honest for this site Jan 13 '16 at 10:51
  • When I use *(res + i) = NULL i got an error of Dereference of out of bound but when I use *(res + i -1) = NULL if my last data inside the res[2] = C it will become null value, the only retain data will be in res[0] = A, res[1] = B. Then for the res[3]=NULL, because this *(res + i -1) = NULL will delete the last value of my array. That's what I get when I use this *(res + i -1) = NULL – Joebert Bisenio Jan 15 '16 at 03:16

1 Answers1

2

In this part of code

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

by trying to access *(res + i), you're going off-by-one. You should write

*(res + i -1) = NULL;

Having said that,

Community
  • 1
  • 1
Sourav Ghosh
  • 133,132
  • 16
  • 183
  • 261
  • Thanks for the answer but if I will do this *(res + i -1) = NULL; the last data inside the array will be deleted. example: when: *(res + i) = NULL; res[0] = A res[1] = B res[2] = C res[3] = D but when *(res + i - 1) = NULL; res[0] = A res[1] = B res[2] = C res[3] = NULL – Joebert Bisenio Jan 14 '16 at 00:54