Welcome, Guest. Please login or register.

Author Topic: char *buf2=new char[size]; problem  (Read 3817 times)

Description:

0 Members and 1 Guest are viewing this topic.

Offline PhatBoiCollier

  • Full Member
  • ***
  • Join Date: Feb 2002
  • Posts: 114
    • Show all replies
    • http://www.tirinoarim.co.uk
Re: char *buf2=new char[size]; problem
« on: November 11, 2004, 11:49:03 AM »
Not at my miggy at the mo but something like...

------------- 8< --------------
Code: [Select]

// Could do char buf1 here and pass &buf1 to function
char buf1[1];
// Initialise to 0 elements
int size=0;
// Initialise to NULL so realloc works properly!
// Could do &quot;char *buf2 = NULL;&quot;, its the same thing!
char buf2[] = NULL;

while (recv(new_fd,buf1,sizeof(buf1),0))
{
    // Increase size of array
    size++;
    // Reallocate buffer (+1 for terminator!)
    realloc(buf2,(size+1)*(sizeof(char));
    // Copy character (-1 because array starts at 0)
    buf2[size-1] = buf1[0];
    // Reset terminator
    buf2[size] = '\0';
    // Print status
    printf(&quot;size: %d\nbuf2: %s\n&quot;,size,buf2);
}

--------------- >8 ------------

should do it.
There are 10 types of people in this world.
Those that understand binary and those that dont.
 

Offline PhatBoiCollier

  • Full Member
  • ***
  • Join Date: Feb 2002
  • Posts: 114
    • Show all replies
    • http://www.tirinoarim.co.uk
Re: char *buf2=new char[size]; problem
« Reply #1 on: November 11, 2004, 04:17:57 PM »
Its broken and crashes horribly?  A bit harsh matey.  I was working from memory (no pun intended).

You are correct though a check on the return value of realloc should be made.  If realloc fails then you are out of memory and so are screwed anyway!

Oh, and dont forget to free buf2, or it may break and crash horribly taking the world with it etc..

Code: [Select]

// Could do char buf1 here and pass &buf1 to function
char buf1[1];
// Initialise to 0 elements
int size=0;
// Initialise to NULL so realloc works properly!
// Could do &quot;char *buf2 = NULL;&quot;, its the same thing!
char buf2[] = NULL;

while (recv(new_fd,buf1,sizeof(buf1),0) && (size>0))
{
    // Increase size of array
    size++;
    // Reallocate buffer (+1 for terminator!)
    if realloc(buf2,(size+1)*(sizeof(char))>0)
    {
        // Copy character (-1 because array starts at 0)
        buf2[size-1] = buf1[0];
        // Reset terminator
        buf2[size] = '\0';
        // Print status
        printf(&quot;size: %d\nbuf2: %s\n&quot;,size,buf2);
    }
    else
    {
        // realloc failed
        printf(&quot;No more memory!\n&quot;);
        // force loop exit
        size = -1;
    }
}
free(buf2);
There are 10 types of people in this world.
Those that understand binary and those that dont.