I have written a small client server program using tcp sockets, and i ran into trouble in retrieving the data brought in by the receive function. Like down below.

char *rec;
    int buff=1024;

You need a char buffer to get the data, but after that i wanted to sort and analyze the data and that was a bit hard to do with a char buffer. It was also hard to covert it to any other format like an array. Finally i came up with something like this.

char *a="Hello World!";
    int b=strlen(a);
    char *c= new char[b];
    int x=0;

It got the job done, but what i wanted to know is, is this the way this is usually done? or is there a better way to do it? if there is what?

Recommended Answers

All 2 Replies

This is a correct way to do it:

int buflen = 1024;
    char *buffer = NULL;
    char *readbytes = NULL;
    int ret = -1;

    buffer = new char[buflen]; // you have to allocate memory for the buffer
    ret = recv(a, buffer, buflen, NULL);

    if(ret == -1)
        // an error occured

    // ret contains the amount of read bytes, use it to avoid processing garbage
    readbytes = new char[ret];
    memcpy(readbytes, buffer, ret);

    // do something with the read bytes

    delete[] readbytes;
    delete[] buffer;

The buffer will contain raw bytes (read bytes and garbage). You can cast them to match some struct or do whatever necessary with them. Remember that those bytes don't have to be printable characters. If you are sure that the received data contains printable characters (e.g. you sent them in your server application), then you could print them.

The second bit isn't correct, but it will compile and run just fine.

char *a="Hello World!";
    int b=strlen(a);
    char *c= new char[b]; // some memory gets allocated (btw, b is the length of a without null)
    c=a; // the address of the allocated memory is lost here
    int x=0;

I guess you wanted to do this:

char *a = "Hello World!";
    int b = strlen(a);
    char *c = NULL; // an unused pointer should be null
    c = new char[b + 1];
    // if c is still null or new[] had thrown an exception, then an error occured
    memcpy(c, a, b + 1);
    int x = 0;
        cout << c[x] << endl;
    delete[] c;
    c = NULL; // the pointer is unused again

Remember to keep a copy of your allocation address and free it with delete when you don't need it anymore. Then either set the pointer to NULL (which is a good programming practice) or don't use it anymore.

Thank you, this was very helpful. I will redo the app using this new input.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, learning, and sharing knowledge.