No, char** arrays don't need to be null terminated.
It is usually done so (especially for char**) so you can iterate over the array until NULL.
E.g. char** argv is null terminated by the standard specifically so you could do something like this:
1 2 3 4
|
while (*argv) {
//foo
++argv
}
|
This isn't considered good practice at all, hence why argv is usually declared as const.
However the bottom line is sure: you don't have to null terminate arrays!
______________________________________________________
As for your code there are two immediate problems that can cause a seg fault.
The
first (which is actually causing the seg fault in this code) is this bit:
1 2 3 4
|
for(int i =0; i <= nRecords; ++i) {
delete[] myCharArray[i];
myCharArray = nullptr;
}
|
You're setting myCharArray to null but in next iteration you're using
myCharArray[i]
.
Of course that line should be
myCharArray[i] = nullptr;
I'll assume that was just a typo, because the
second one (which can
potentially cause problems and which may have actually been the culprit in your original code) is much more elusive.
First, your create_array() is actually creating
eleven strings because you're using <= in
|
for(int i =0; i <= nRecords; ++i)
|
.
Not ten. Hence myCharArray will also hold 11 chars. When you do:
|
myCharArray[nRecords] = nullptr;
|
You're actually erasing a valid 11th pointer to a string, thus causing a memory leak and potentially opening a segfault opportunity in all subsequent for's which use <=!
The reason you did not get a segfault this time is because std::cout and delete[] are leient toward accepting a NULL pointer.
If you had decided to do something with
myCharArray[i]
e.g.:
You would have gotten a segfault.
Recommendation: Stop using <= in for loops which start from 0.
Edit: I had to reformat this post a bit so it's easier to read.