Welcome, Guest. Please login or register.

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

Description:

0 Members and 1 Guest are viewing this topic.

Offline nex4060

  • Full Member
  • ***
  • Join Date: Sep 2004
  • Posts: 238
    • Show all replies
Re: char *buf2=new char[size]; problem
« on: November 11, 2004, 09:48:49 AM »
sounds like you are trying to use a C++ code on a C compiler. The new C++ function is called malloc in C. I think the syntax is:

char *buf2 = (char*) malloc((sizeof(char)*"an integer"));

if I remember corretly

btw:

int size=0;
char *buf2=new char[size];

seems wrong because you make a array with no length, hence nothing will be allocated! size should at least be size=1 the you would get a single char in your array. otherwise you get a memory violation.
memcpy dosen't make allocations only copies between memory-locations, hence it could/should fail if the array is zero bytes long.
I might be wrong here, and new char[0] sees that you want to make a single char as in new char or new char[1]
\\"Computer games don\\\'t affect kids; I mean if Pac-Man affected us as kids, we\\\'d all be running around in darkened rooms, munching magic pills and listening to repetitive electronic music.\\"
- Kristian Wilson, Nintendo, Inc,1989  :lol:
 

Offline nex4060

  • Full Member
  • ***
  • Join Date: Sep 2004
  • Posts: 238
    • Show all replies
Re: char *buf2=new char[size]; problem
« Reply #1 on: November 11, 2004, 10:15:19 AM »
@Piru

HAHA!.. okey think you misunderstood me:

malloc( sizeof(char) * "an integer" ); as in
malloc( sizeof(char) * 5); for exampel :-)
here you would get an array og 5 chars :-)
\\"Computer games don\\\'t affect kids; I mean if Pac-Man affected us as kids, we\\\'d all be running around in darkened rooms, munching magic pills and listening to repetitive electronic music.\\"
- Kristian Wilson, Nintendo, Inc,1989  :lol:
 

Offline nex4060

  • Full Member
  • ***
  • Join Date: Sep 2004
  • Posts: 238
    • Show all replies
Re: char *buf2=new char[size]; problem
« Reply #2 on: November 11, 2004, 11:37:08 AM »
you have made an memory-voilation.

you have to make a new array and copy the old one. memcpy dosn't make a new array or enlarges it for you!

char buf1[1];
int size=1;
char *buf2=malloc(sizeof(char)*size);
char *temp = 0;

while(recv(new_fd,buf1,sizeof(buf1),0))
{
   temp = malloc(sizeof(char)*size);
   memcpy(temp,buf2,sizeof(buf2));
   memcpy(temp+size-1,buf1,sizeof(buf1));
   free(buf2);
   buf2 = temp;
   temp = 0;
   size++;

   printf("size: %d\n",size);
   printf("buf2: %s\n",buf2);
};

that should work
\\"Computer games don\\\'t affect kids; I mean if Pac-Man affected us as kids, we\\\'d all be running around in darkened rooms, munching magic pills and listening to repetitive electronic music.\\"
- Kristian Wilson, Nintendo, Inc,1989  :lol: