Basically in the code below, my final array does not seem to have the contents from function1(). Any ideas on why I can’t get this to work ? Thanks.
#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]);
}
Following are the mistakes that I observed in your code.
You wrote
Now there is no need to do this
pointer1 = &temp, name of any array itself is a pointer.Hence you can simply do
But wait!
Does pointer1 has enough space to store the contents of temp[]? In your code you have not assigned any space to pointer1, which is likely to crash your program.
The correct way to do it is
here before copying any value into pointer1 we made sure that it has got enough space.
No need to cast malloc() retrun value. In
sizeof( temp) + 11 is added for null character. Then we did memset() which filled the memory pointed to by pointer1 with null. Just good and healthy practice.Then you
Again, does pointer1 has enough space for contents of pointer3? Do you own the memory area pointed by
pointer1 + sizeof(temp)? It too will crash your program.Now you either use
realloc()or assign a bigger space to pointer1 withmalloc()at earlier stage.Why
sizeof ( the temp array)here? Don't you think it should have the number of bytes in pointer3?Finally in the definition of
function1()What does
array2do? Nothing! Then it should be removed.To return just use
which means
pointer2is also useless.Hope it helps.