Thread: problem with data cast

  1. #1
    Registered User
    Join Date
    Sep 2005

    problem with data cast

    Hi everybody!!!!! I need to pass an int array through send() function and I do it in this way:

    server side:
    int array[10];
    char* buffer;
    buffer = (char*)malloc(20);
    buffer = (char*) array;
    send(socket, buffer, sizeof(buffer), 0);

    client side:
    int *array;
    char *buf;
    recv(socket, buf, 20, 0);
    array = (int *)buf;

    According to you, what's wrong? Data I receive have different values from those I send. Where is the problem?

  2. #2
    Frequently Quite Prolix dwks's Avatar
    Join Date
    Apr 2005
    array = (int *)buf ? Can recv() accept an integer parameter?

    Seek and ye shall find. quaere et invenies.

    "Simplicity does not precede complexity, but follows it." -- Alan Perlis
    "Testing can only prove the presence of bugs, not their absence." -- Edsger Dijkstra
    "The only real mistake is the one from which we learn nothing." -- John Powell

    Other boards: DaniWeb, TPS
    Unofficial Wiki FAQ:

    My website:
    Projects: codeform, xuni, atlantis, nort, etc.

  3. #3
    and the hat of int overfl Salem's Avatar
    Join Date
    Aug 2001
    The edge of the known universe
    > buffer = (char*)malloc(20);
    1. you cast malloc - this is not necessary in C - see the FAQ
    2. you seem to assume that sizeof(int) is 2. If this really is the case, your compiler is too old

    > buffer = (char*) array;
    You just lost the memory you allocated.

    > send(socket, buffer, sizeof(buffer), 0);
    1. you don't check the return result.
    2. sizeof() on a pointer gives you the size of the pointer, not the size of the thing it points at.

    result = send(socket, array, sizeof(array), 0);

    > According to you, what's wrong?
    Pretty much every line of code you've written has problems.
    Start by
    a) learning C
    b) reading all the tutorials in the announcements on this forum
    If you dance barefoot on the broken glass of undefined behaviour, you've got to expect the occasional cut.
    If at first you don't succeed, try writing your phone number on the exam paper.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. problem with data in allocated memory
    By supi in forum C Programming
    Replies: 3
    Last Post: 06-09-2008, 02:06 AM
  2. problem reading mixed data...
    By coralreef in forum C Programming
    Replies: 3
    Last Post: 11-08-2006, 05:29 PM
  3. [question]Analyzing data in a two-dimensional array
    By burbose in forum C Programming
    Replies: 2
    Last Post: 06-13-2005, 07:31 AM
  4. Binary Search Trees Part III
    By Prelude in forum A Brief History of
    Replies: 16
    Last Post: 10-02-2004, 03:00 PM
  5. C diamonds and perls :)
    By Carlos in forum A Brief History of
    Replies: 7
    Last Post: 05-16-2003, 10:19 PM