1

i have the following code :

int * buffer;
buffer = (int *) malloc((320*240)*sizeof(int));

after populating the buffer with data i want to send it using UDP sockets, however it seems that currently my following send function sends just 4 byte (of data) and not ((320*240)*sizeof(int)):

iError = send(MySock, (char *)(buffer) , sizeof(buffer), 0);

i am tried different combinations on the second and third fields of the send function but it doesn't work, What is the correct syntax should i use?

BTW i have to define the buffer as int * since it being used by other library that has to get that as int *.

Hanan
  • 1,169
  • 3
  • 23
  • 40
  • Read any [C FAQ](http://stackoverflow.com/questions/12760229/stack-pointer-difference-char-pointer-and-array). – Lundin Jan 18 '13 at 14:05
  • 1
    Side note, it seems like a lot of data to transfer in one go over UDP. You know that UDP does not guarantee proper delivery right? – netcoder Jan 18 '13 at 14:16

4 Answers4

4

This is because in your send() call, you specify sizeof (buffer). This is the size of the variable buffer, which is the size of a pointer, which happens to be four bytes on your system. It's NOT the size of the block that the pointer points at, that information is not available.

You must specify 320 * 240 * sizeof *buffer to get the proper size. Of course, even better is to factor this out into a variable:

int *buffer;
const size_t buffer_size = 320 * 240 * sizeof *buffer;

if( (buffer = malloc(buffer_size)) != NULL )
{
  /* ... fill buffer ... */
  send(MySock, buffer, buffer_size, 0);
}

There's no need to cast, malloc() returns void * and send() accepts it.

Note that doing very large send()s over UDP might not work, due to IP fragmentation. It's better to send it using many small datagrams, in my experience.

Community
  • 1
  • 1
unwind
  • 391,730
  • 64
  • 469
  • 606
2

sizeof(buffer) is the size of a pointer type, which is apparently 4 bytes on your system.

Keep track of the length of your buffer (320 * 240 * sizeof(int)) and pass that to send().

Michael Foukarakis
  • 39,737
  • 6
  • 87
  • 123
1

use

send(MySock, (char *)(buffer) , (320*240)*sizeof(int), 0);

instead of

send(MySock, (char *)(buffer) , sizeof(buffer), 0);

buffer is a pointer type and the size of a pointer is 4 byte for your system (for other system it could be 8 bytes (like 64 bits machines)

you have to put the size of allocated memory and not the size of the pointer. The size of allocated memory is not the same of the size of a pointer pointing on

MOHAMED
  • 41,599
  • 58
  • 163
  • 268
0

The error is in this line

iError = send(MySock, (char *)(buffer) , sizeof(buffer), 0);

You are telling send to send the size of the pointer, which is 4 bytes. you need to give it (320*240)*sizeof(int).

stdcall
  • 27,613
  • 18
  • 81
  • 125