When writing to a file, in addition to the text, various symbols are added, although if you call a function without a variable with text, then everything is fine.

What could be the problem?

writedata(dir, "hello moto kek lol test lul mur meow"); - все хорошо 

 char* kik = getdata(); writedata(dir, kik); - все плохо 

 void writedata(char* file, char* data) { ofstream fout(file, ios_base::binary); fout << data; // запись строки в файл fout.close(); // закрываем файл return; } 

upd:

 int sock; int bytes_read; struct sockaddr_in server; WSADATA ws; char server_reply[2048]; memset(&server_reply, 0, sizeof(server_reply)); const int WINSOCK_VERSION = MAKEWORD(2, 2); WSAStartup(WINSOCK_VERSION, &ws); sock = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP); server.sin_addr.s_addr = inet_addr(ip); server.sin_family = AF_INET; server.sin_port = htons(6896); if (connect(sock, (struct sockaddr *)&server, sizeof(server)) < 0) { return "connectfail"; } send(sock, msg, strlen(msg), 0); bytes_read = recv(sock, server_reply, sizeof(server_reply), 0); return server_reply; 
  • 3
    If this function getdata (); returns a pointer to the local variable of the function, then, indeed, everything will be bad. Another cause of the problem may be that the string does not end in zero. Therefore, show the getdata () function; - Vlad from Moscow

2 answers 2

The server_reply array is a local variable of the getdata function.

 char server_reply[2048]; 

When exiting a function, this local variable ceases to exist. Therefore, a pointer to this array returned from a function is not valid. As a result, the program has an undefined behavior.

You could at least declare this local variable as having static memory, provided that the function is used in a single-threaded environment, or as having the qualifier thread_local in a multi-threaded environment. For example,

 static char server_reply[2048]; 

In addition, in order to treat an array as containing a string, this sentence should read the number of bytes one less than the size of the array.

 bytes_read = recv(sock, server_reply, sizeof(server_reply) - 1, 0); 

It would be better to write a function in such a way that it receives a buffer as an argument, and returns the number of bytes read.

    In addition to the text, various symbols are added.

    This suggests that your text is most likely not completed with a null character, as required by

     fout << data; // запись строки в файл