0

I have declared char data[101]; and after that read message from socket into it(server - client communication). After the message is displayed on screen I want to clear/empty that char array. I tried memset(data, 0, sizeof(data)) and bzero(data, sizeof(data)); And I think it still didn't clear it. At the output after receiving the first message I also get some weird characters: ��|V� and after them also the message is shown. Now I don't know if that is from clients or servers side. I tried to clear it on both but the result isn't any different.

This is how I send message:

char data[101];
read(0, data, 101);
dprintf(socket_fd, data);
bzero(data, sizeof(data));
hypr2
  • 43
  • 9

2 Answers2

1

The code you show is very problematic:

char data[101];
read(0, data, 101);
dprintf(socket_fd, data);

There are three major problems with it:

  1. You don't check for errors, which means if the read call fails you will send uninitialized data.

  2. You don't terminate the input as a string, which means you might go out of bounds when sending.

  3. If the input contains printf formatting sequences then dprintf will attempt to read arguments that doesn't exist and you will have undefined behavior (and a really big security hole).

The following code should fix all of the above:

char data[101];  // Place for a 100-character string, plus terminator

ssize_t bytes_read = read(STDIN_FILENO, data, sizeof(data) - 1);  // -1 since we need space for terminator

// Make sure the read call went okay
if (bytes_read > 0)
{
    // There was no error or end-of-file
    data[bytes_read] = '\0';  // Terminate as a string

    dprintf(socket_fd, "%s", data);  // Send the data
}

On the receiving side you of course need to add error checking when receiving the data, attempt to receive one byte less than the data-buffer size, and terminate the data-buffer before printing it.

Some programmer dude
  • 400,186
  • 35
  • 402
  • 621
  • Why not use `fgets()`? This will automatically check out of boundary issue in case input characters exceed 101. Is there a reason to use `read()`? Thanks – Nguai al May 23 '17 at 08:08
  • This is the only sane solution presented. Not unusually, another one with a cycle-wasting 'zero all the buffer even though you are about to load it' answer has been accepted. – ThingyWotsit May 23 '17 at 08:54
1

Here is another alternative solution

//Declare and initialize to NUL characters.
char data[101] ="";  

//fgets() will take care of out of boundary issue.
 if (fgets(stdin, data, sizeof(data))
    dprintf(socket_fd, "%s", data);  // Send the data
Nguai al
  • 958
  • 5
  • 15