Click here to Skip to main content
15,892,005 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I want to merge the 2 arrays in the main function. But for some reason, even though I can get array3[0] and array3[1] to have the right values, when they are copied into the packet, their values are different. Any idea why ?
Thanks for your help.

#include <stdio.h>
#include <string.h>
#include <stdlib.h>

unsigned char *function1() 
{
    unsigned char array2[] = { 0x4a,0xb2 };
    return (array2 );
}

main()
{
   unsigned char temp[] = { 0xaa, 0x0b, 0x03,0x04,0x05,0x06,0x07,0x08,0x09 };
   unsigned char x[2];
   unsigned char *packet;
   int pkt_len;
   pkt_len = sizeof(temp) + sizeof(x);
   packet = (unsigned char*) malloc ( pkt_len +1);

   memset( packet, 0x00, pkt_len +1);
   unsigned char *pointer1 = malloc ( sizeof(temp) + 1);

   memset( pointer1, 0x00, sizeof(temp) +1);
   memcpy (pointer1, temp, sizeof(temp) );

   memcpy (packet, pointer1, sizeof(temp) );
   printf("\nPacket before copy is 0x%x\n", packet[8]);

   unsigned char *array2 = malloc ( sizeof (x) + 1)  ;
   array2 = (char *)function1();
   printf("\nArray2 is 0x%x\n", array2[0]);
   memcpy (packet + sizeof(temp), array2, sizeof(x) );
   printf("After copy, Packet contents are 0x%x\n", packet[9]);
}
Posted
Updated 25-Jun-10 9:36am
v3

1 solution

First off: Are you sure you want to return an address of a local variable from function1()? There's no guarentee that array2 will point to a meaningful block of memory when the function returns.

Secondly: Are you sure your program is valid C? I'm not an expert on C anymore but declaring variables after non declaring statements was a complete no-no in C89. array2 and pointer1 are the variables I'm looking at in particular.

Thirdly: You've got loads of redundant copying and memsetting going on so it's a bit hard to see what you're actually intending to do. For example:

memset( pointer1, 0x00, sizeof(temp) +1);  
memcpy (pointer1, temp, sizeof(temp) );


could be replaced with:

memcpy ( pointer1, temp, sizeof temp );
pointer1[ sizeof temp] = 0x00;


Fourthly: In C you don't need to cast the return value of malloc. void * is compatible with any pointer type.

Fifthly: Whenever an experienced C programmer sees sizeof( x ) they start looking for a type called x. Leave off the braces when taking the size of an object.

Sixth: What's the point of pointer1? It seems totally redundant.

If all you want to is dynamically create a lump of memory and copy two other arrays into it you can do it in about three lines:
- allocate the memory
- copy the first array into the allocated memory
- copy the second array into the allocated memory after the first array

Cheers,

Ash
 
Share this answer
 
v2

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900