
allocating memory for a char **
Quote:
> Hi, I am a C newbie and I have the following question:
> I have a an array of arrays of chars declares as char ** and I would
>like
> to dynamically add more strings. here is what I did:
> char **lines;
> char **temp;
> if (new_string) {
I take it new_string was defined as "char *newstring;"?
Quote:
> temp = lines;
This effectively does nothing as lines has not had anything allocated
to it; the contents are undefined.
Quote:
> while (temp)
> temp++;
This is almost certainly not doing what you want. Short version: The
while loop runs until temp is "zero", which, since temp is a pointer,
is likely to be a NULL pointer.
A "simple" method of doing what it looks like you want would be to
check against the contents of temp, or to put it another way, check
against what temp points to. This does require that the end of your
array has been initialized to a NULL pointer (or whatever value you're
checking it against).
In any case, you'll need to have alloc()'d something to lines in the
first place before this will work at all.
Quote:
> lines = (char **)realloc(lines,sizeof(char *));
This is dangerous, as realloc() returns a NULL if (for some reason) it
can't fulfill your request. If that happens, you'll have just sent the
block lines used to point to off into hyperspace. At the very least,
have another temporary variable to store the pointer returned from
realloc() until you check it to make sure it's not NULL.
Quote:
> *temp = new_string;
> }
> This does not work as the call to realloc segfaults. Does anyone have
>a
> working (and, therefore, BETTER) way of doing this? Or could anyone tell
> me why the realloc call segfaults?
The why is that you can't realloc() until you've done a malloc() (or,
at the very least, have initialized lines to NULL to tell realloc() to
act as malloc()). The realloc() function changes the size of a
previously allocated block of memory, which, in this case, lines must
point to. When lines is declared, it's not being initialized, and so
points to a undefined location of memory.
Quote:
You're welcome.
There are a few other points in there that likely won't do what you
expect, but they should be visible with the allocation issues cleared
up.
(BTW, watch the long lines; they don't easily lend themselves to
quoting.)
--
PGP key fingerprint = 48 94 7A 54 59 B6 C0 77 1F F6 94 55 0C 55 51 C4
+Accept: text/plain; charset=ISO-8859-*,UTF-*
--