Array Return

closed account (G26pX9L8)
I have made a function for receiving data on a socket connection. Now what I want is that function returns the received data. The data could be anything so that's the reason why I chose for a char.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
char* FuncRecv(SOCKET sock)
{
    char buffer[256]="";
    ZeroMemory(buffer, sizeof(buffer));

    if(recv(sock,buffer,sizeof(buffer),0) == SOCKET_ERROR)
    {
        closesocket(client);
        WSACleanup();
    }
    //MessageBox(NULL, buffer, "QRecv", MB_OK);

    return (char*) buffer;
}

But this code only returns one character and that is logical because buffer is declared as a char instead of a char*, but by doing that I get a runtime error. Any solutions how to solve this?
Last edited on
Your variable named "buffer" is the stack area.When your program run out this function,the stack area will be destroyed.
You can use a global array for "buffer".
e.g:

1
2
3
4
5
char buffer[256];
char * FuncRecv(SOCKET sock)
{
     ...
}
use a global array or pass in a buffer as a parameter and let the function set the buffer data
closed account (G26pX9L8)
tnx both, its working now, I am using a global array.
Don't pollute the global scope. It's bad.
And why are you closing the socket inside your recv wrapper?

1
2
3
4
inline int FuncRecv(SOCKET sock, char* buffer, int size)
{
  return recv(sock, buffer, size, 0);
}


For some C complier,there are no inline.You have to define global scope to transfer data.
Especially in embeded system.almost 80% of them use the standard C or cutted C.
How to solve this bug depend the situation.All rules may have to change for special situation.
Topic archived. No new replies allowed.