0
char* quickrecv(SOCKET* sock) {
    int ilen;
    char* len = (char*)malloc(4);
    recv(*sock, len, 4, 0);
    memcpy(&ilen, len, sizeof(ilen));
    char* buf = (char*)malloc(ilen);
    //no matter what value ilen is, sizeof buf is always 4 when it shouldn't be
    recv(*sock, buf, ilen, 0);
    return buf;
}

Hello everyone! Bit of a noob question here. I am creating a simple socket protocol in c++ for fun. I tried making a receive function for convenience however it is not working. When I receive the data, it either adds characters to the output to make the output four characters long or it cuts off the output so it is only four characters long. I did some debugging and apparently my char pointer "buf" is only the size of four bytes. Even though "ilen" is different every time (I checked with printf), buf ends up only being four bytes of allocated memory. Why is the size of buf only four even though the parameter for malloc is different everytime? Thank you!

  • 5
    *sizeof buf is always 4* - because it is the size of the pointer – user7860670 Jun 22 '20 at 14:54
  • 1
    Related: [Determine size of dynamically allocated memory in C - Stack Overflow](https://stackoverflow.com/questions/1281686/determine-size-of-dynamically-allocated-memory-in-c) – MikeCAT Jun 22 '20 at 14:55
  • 2
    `sizeof` only cares about the type - `sizeof(buf)` is equivalent to `sizeof(char*)`. – molbdnilo Jun 22 '20 at 15:02
  • you *suppose* `sizeof(int)` is 4 but that can be false, better use an `int32_t`, also the caller of *quickrecv* has no way to know the size of the returned buf, better to have the output parameter `int32_t * ilen` to also give the length to the caller (of course in C++ you can replace your `char*` by a `std::vector` to both return the bytes and their number) – bruno Jun 22 '20 at 15:11

0 Answers0