strings and malloc 
Author Message
 strings and malloc

I'm trying to allocate memory for a an array of 6 strings... do i
allocate for the array itself or for each element individually?

Thanks...



Sat, 02 Nov 2002 03:00:00 GMT  
 strings and malloc


Quote:
>I'm trying to allocate memory for a an array of 6 strings... do i
>allocate for the array itself or for each element individually?

>Thanks...

Both:

    - calloc() for the _array_
    - malloc for each of the strings

HTH
Georg Pohl

--

Web:   http://www.online-club.de/~Eulenspiegel
       Download freeware for DOS, C libraries



Sat, 02 Nov 2002 03:00:00 GMT  
 strings and malloc

Quote:

> I'm trying to allocate memory for a an array of 6 strings... do i
> allocate for the array itself or for each element individually?

Both. You need memory to hold the pointers to the start of each string
(in your case for 6 char pointers; therefore malloc(6*sizeof(char *)) or
even malloc(6*sizeof(*sixstrings)) or whatever your var is called),
_and_ you need memory to hold the strings (in your case 6 repetitions of
malloc(strlen(nextstring)+1) or malloc(sizeof(nextstring)), depending.)

Richard



Sat, 02 Nov 2002 03:00:00 GMT  
 strings and malloc

: I'm trying to allocate memory for a an array of 6 strings... do i
: allocate for the array itself or for each element individually?

: Thanks...

You don't need to malloc() memory for the array itself, you can have it
as static. But you do need to malloc() memory for the elements. So you
have a static array...
char *mikemoosestrings[6];
and then you use malloc() for each element individually...
for (i=0; i<6; i++)
  mikemoosestrings[i]=malloc({*filter*}Y_BIG);
Hope that helps!

--

| Kingpriest of "The Flying Lemon Tree" G++ FR FW+ M- #80 D+ ADA N+++ |
| http://www.*-*-*.com/ ~palaste       W++ B OP+                     |
\----------------------------------------- Finland rules! ------------/

"How come even in my fantasies everyone is a jerk?"
   - Daria Morgendorfer



Sat, 02 Nov 2002 03:00:00 GMT  
 strings and malloc

Quote:

>     - calloc() for the _array_
>     - malloc for each of the strings

calloc() for an array of pointers? I don't think so. The other way
around would be more correct, though I wouldn't necessarily use calloc()
for a string.

Richard



Sat, 02 Nov 2002 03:00:00 GMT  
 strings and malloc

Richard Bos schrieb in Nachricht

Quote:

>>     - calloc() for the _array_
>>     - malloc for each of the strings

>calloc() for an array of pointers? I don't think so. The other way
>around would be more correct, though I wouldn't necessarily use
calloc()
>for a string.

I use it like:

    #define ITEMS  (10)
    #define WIDE   (20)

    char **tmp;

    void foo(void)
    {
        char **tmp;
        int  n;

        tmp = calloc(ITEMS, sizeof(char **));
        for (n = 0; n < ITEMS; n++)
            tmp[n] = malloc(WIDE + 1);
    }

Is this not correct?

Georg



Sat, 02 Nov 2002 03:00:00 GMT  
 strings and malloc

Quote:

>         tmp = calloc(ITEMS, sizeof(char **));

> Is this not correct?

Excerpt from the FAQ, question 7.31:

Q: ...Is it safe to take advantage of calloc's zero-filling?...
A: ...The zero fill is all-bits-zero, and does not therefore guarantee
      useful null pointer values...

Richard



Sat, 02 Nov 2002 03:00:00 GMT  
 strings and malloc

Richard Bos schrieb in Nachricht

Quote:

>>         tmp = calloc(ITEMS, sizeof(char **));

>> Is this not correct?

>Excerpt from the FAQ, question 7.31:

>Q: ...Is it safe to take advantage of calloc's zero-filling?...
>A: ...The zero fill is all-bits-zero, and does not therefore
guarantee
>      useful null pointer values...

I got it - thank you Richard

Georg



Sat, 02 Nov 2002 03:00:00 GMT  
 strings and malloc

Quote:
>I'm trying to allocate memory for a an array of 6 strings... do i
>allocate for the array itself or for each element individually?

It depends on what exactly you want to do.  Your description of the
problem is incomplete.  Here are a few possibilities:

1. You don't know anything about the strings at compile time, you can
   only obtain their lengths at run time:

    #define N 6
    char *array[N];

    for (i = 0; i < N; i++)
        array[i] = malloc(len[i]);

  I assumed that the lengths are available in the len array.

2. All the strings have the same size, available in "size":

    char *p = malloc(N * size);
    for (i = 0; i < N; i++)
        array[i] = p + i * size;

3. As above, but you know the size at compile time and you don't want
   the allocation to be dynamic:

    #define SIZE 20
    char array[N][SIZE];

4. You want the array of pointers to be dynamically allocated, too:

    char **array = malloc(N * sizeof *array);
    /* now you can allocate memory for the strings themselves and initialise
       the array of pointers, as in the first two examples above */

5. You know the contents of the array at compile time and you want
   static allocation:

    char *array[] = {"one", "two", "three", "four", "five", "six"};

Note that I have implicitly reused the declarations made in previous
examples, where needed, and I omitted the error checking on the malloc()
calls.

If you want the allocated strings to be already initialised as empty
strings, use calloc instead of malloc to allocate the string memory.

Dan
--
Dan Pop
CERN, IT Division

Mail:  CERN - IT, Bat. 31 1-014, CH-1211 Geneve 23, Switzerland



Sat, 02 Nov 2002 03:00:00 GMT  
 strings and malloc

Quote:

> 1. You don't know anything about the strings at compile time, you can
>    only obtain their lengths at run time:

>     #define N 6
>     char *array[N];

>     for (i = 0; i < N; i++)
>    array[i] = malloc(len[i]);

>   I assumed that the lengths are available in the len array.

I hesitate to point this out, but...  I'd suggest either renaming
len[] to size[] or inserting `+ 1' into the malloc() call, in
order that the allocation of space for the null terminator
becomes clear.  Unless, of course, you're not assuming the use of
null-terminated strings.


Sat, 02 Nov 2002 03:00:00 GMT  
 strings and malloc

Of course you want
#include <stdlib.h>
for calloc() and malloc()

Quote:
>    #define ITEMS  (10)
>    #define WIDE   (20)

Drop these useless parens

#define ITEMS  10
#define WIDE   20

Quote:
>    char **tmp;

What is this made for ? I guess a copy & paste instead of a cut & paste...

Quote:
>    void foo(void)
>    {
>        char **tmp;
>        int  n;

>        tmp = calloc(ITEMS, sizeof(char **));

This is a complicated and hard to maintain way for

        tmp = calloc(ITEMS, sizeof *tmp);
Ou course you need an error checking here...

Quote:
>        for (n = 0; n < ITEMS; n++)
>            tmp[n] = malloc(WIDE + 1);

... and here

Quote:
>    }

There is nothing wrong to use calloc() to allocate an array. Just bear in
mind that all bits to 0 does not mean NULL or 0.0.

Be also careful that if one malloc() fails in the for-loop, you must free()
the previoulsy allocated blocks and the array too, before leaving the
program. So, you need a "garbage collector"

void clean(char **tmp, size_t len)
{
   if (tmp)
   {
   size_t i;

      for(i=0;i<len;i++)
      {
         if(tmp[i])
         {
            free(tmp[i]);
            tmp[i]=NULL;
         }
      }
      free(tmp);
   }

Quote:
}

In order to work correctly, the tmp array must be filled with explicit NULLs
just after being allocated.

void clear(char **tmp, size_t len)
{
   if (tmp)
   {
   size_t i;

      for(i=0;i<len;i++)
      {
         tmp[i]=NULL;
      }
   }

Quote:
}

*** uncompiled or tested ***
--
-hs- "Stove"
CLC-FAQ: http://www.eskimo.com/~scs/C-faq/top.html
ISO-C Library: http://www.dinkum.com/htm_cl
"Show us your source code, and let us, like
rapacious vultures half-crazed by starvation, rip it to shreds until
there's practically nothing left" --Richard Heathfield CLC


Sun, 03 Nov 2002 03:00:00 GMT  
 strings and malloc

wrote in comp.lang.c:

Aside from what Richard said:

Quote:
> Richard Bos schrieb in Nachricht


> >>     - calloc() for the _array_
> >>     - malloc for each of the strings

> >calloc() for an array of pointers? I don't think so. The other way
> >around would be more correct, though I wouldn't necessarily use
> calloc()
> >for a string.

> I use it like:

>     #define ITEMS  (10)
>     #define WIDE   (20)

>     char **tmp;

>     void foo(void)
>     {
>         char **tmp;
>         int  n;

>         tmp = calloc(ITEMS, sizeof(char **));

          tmp = calloc(ITEMS, sizeof(char *));

tmp is a pointer to pointer to char.  What it points to is merely a
pointer to char, or an array of pointers to char.

Or even better:

          tmp = calloc(ITEMS, sizeof *tmp);

Even if you change what the pointer points to, the code stays correct.

Quote:
>         for (n = 0; n < ITEMS; n++)
>             tmp[n] = malloc(WIDE + 1);
>     }

> Is this not correct?

> Georg

Jack Klein
--
Home: http://jackklein.home.att.net


Sun, 03 Nov 2002 03:00:00 GMT  
 strings and malloc

Quote:


>Of course you want
>#include <stdlib.h>
>for calloc() and malloc()

>>    #define ITEMS  (10)

>>    #define WIDE   (20)

>Drop these useless parens

>#define ITEMS  10
>#define WIDE   20

No, they are needed in case some powerful operator comes along whose
precedence can rip apart even the strong force that holds the characters
of a number token together.  :) :)

--
#exclude <windows.h>



Sun, 03 Nov 2002 03:00:00 GMT  
 strings and malloc
Kaz Kylheku a crit dans le message ...

Quote:
>>>    #define ITEMS  (10)
>>>    #define WIDE   (20)

>>Drop these useless parens

>>#define ITEMS  10
>>#define WIDE   20

>No, they are needed in case some powerful operator comes along whose
>precedence can rip apart even the strong force that holds the characters
>of a number token together.  :) :)

Ha ha ! The magnet operator ... not in C. In C+++ perharps...

--
-hs- "Stove"
CLC-FAQ: http://www.eskimo.com/~scs/C-faq/top.html
ISO-C Library: http://www.dinkum.com/htm_cl
"Show us your source code, and let us, like
rapacious vultures half-crazed by starvation, rip it to shreds until
there's practically nothing left" --Richard Heathfield CLC



Sun, 03 Nov 2002 03:00:00 GMT  
 strings and malloc


Quote:
>Georg Pohl a crit dans le message


Quote:

>Of course you want
>#include <stdlib.h>
>for calloc() and malloc()

Of course, I posted only an example source snipsel :-)

Quote:
>>    #define ITEMS  (10)

>>    #define WIDE   (20)

>Drop these useless parens

NO! I always put values of #defines into parens. Makes live easier in
case of error in use of macros

Quote:

>#define ITEMS  10
>#define WIDE   20

>>    char **tmp;
>What is this made for ? I guess a copy & paste instead of a cut &

paste...

Only an example ...

Quote:

>>    void foo(void)
>>    {
>>        char **tmp;
>>        int  n;

>>        tmp = calloc(ITEMS, sizeof(char **));

>This is a complicated and hard to maintain way for

>        tmp = calloc(ITEMS, sizeof *tmp);

Yes!!!

Quote:
>Ou course you need an error checking here...

As said: an example only

Quote:

>>        for (n = 0; n < ITEMS; n++)
>>            tmp[n] = malloc(WIDE + 1);

>... and here

>>    }

>There is nothing wrong to use calloc() to allocate an array. Just
bear in
>mind that all bits to 0 does not mean NULL or 0.0.

Very urgent!

Quote:
>Be also careful that if one malloc() fails in the for-loop, you must
free()
>the previoulsy allocated blocks and the array too, before leaving
the
>program. So, you need a "garbage collector"

>void clean(char **tmp, size_t len)
>{
>   if (tmp)
>   {
>   size_t i;

>      for(i=0;i<len;i++)
>      {
>         if(tmp[i])
>         {
>            free(tmp[i]);
>            tmp[i]=NULL;
>         }
>      }
>      free(tmp);
>   }
>}

>In order to work correctly, the tmp array must be filled with
explicit NULLs
>just after being allocated.

>void clear(char **tmp, size_t len)
>{
>   if (tmp)
>   {
>   size_t i;

>      for(i=0;i<len;i++)
>      {
>         tmp[i]=NULL;
>      }
>   }
>}

>*** uncompiled or tested ***

clean() and clear() ares VERY important and useful. Thanks for the
extension of the short example.

Georg Pohl



Sun, 03 Nov 2002 03:00:00 GMT  
 
 [ 16 post ]  Go to page: [1] [2]

 Relevant Pages 

1. dynamically adding storage to a character string with malloc()

2. Q:selfdefined C-String and malloc

3. string using malloc

4. Strings and Malloc

5. two question string/malloc

6. malloc truncates string

7. Using malloc with an array of strings

8. Newbie question: using malloc() to create a string?

9. free()ing a malloc()ed string in function

10. A minor problem regarding string input and malloc()

11. strange string/malloc problems

12. Malloc: Problem with Dynamic string array.

 

 
Powered by phpBB® Forum Software