2

I'm reading in pieces of a jpg captured from a udp stream and I have the following:

#define BUF_SIZ 1066

int main(int argc, char *argv[])
{
    int ptr;
    uint8_t buf[BUF_SIZ];
    uint8_t jpg[BUF_SIZ * 256];

repeat:
    //... Check if first packet

    //... fill buf after finding first packet

    // append buf array to jpg array passing header
    memcpy(&jpg[ptr], &buf[46], numbytes - 46);
    ptr += (numbytes - 46);

    ... check if last packet.

    ... goto repeat if not last packet

ending:
    ... process jpg array

This is working but I don't think it's right (I'm new to c) and I'm getting occasional random segfaults).

I'm doing other things in between packets so I need to finish capturing the package asap

John Smith
  • 3,493
  • 3
  • 25
  • 52
  • You've got three magic numbers that you need to justify. **1066**: UDP packets can be much larger, so why 1066. **46**: Are you sure the header is always 46 bytes. Are you checking anything the header to make sure the header (and the remainder of the packet) are valid. **256**: That puts a limit of about 256K on the total image size. Seems small to me. How are you making sure that you don't run off the end of the `jpg` array. – user3386109 Mar 24 '18 at 00:48
  • add some sanity checks; e.g. `numbytes >= 46`, `sizeof buf >= numbytes`, `sizeof jpg + 46 - ptr >= numbytes` – ensc Mar 24 '18 at 00:52
  • 1
    Hmmm, 1066 is a noted [year](https://en.wikipedia.org/wiki/Battle_of_Hastings). Perhaps this is the Hastings.c file? – chux - Reinstate Monica Mar 24 '18 at 01:04
  • It occurs to me that the code doesn't show `ptr` being initialized. You *do* need to initialize it before using it. – user3386109 Mar 24 '18 at 01:22
  • So from the sound of it, no one is unhappy with the fact I'm using the pointers the way I am? I'll work on the checks, but I just wondered if I was doing the actual memcpy wrong. – John Smith Mar 24 '18 at 01:27
  • The `memcpy` looks fine to me. – user3386109 Mar 24 '18 at 05:42

1 Answers1

1

things to check before doing memcpy:

ptr >= 0
ptr+numbytes < BUF_SIZ * 256
numbytes >= 46
ptr+numbytes > 0

That last one may seem strange but there may be values of numbyets that fail there but satisfy the other three checks. (but if you can prove that numbytes is well below INT_MAX you don't need tat check)

Jasen
  • 11,837
  • 2
  • 30
  • 48