diff --git a/jdmarker.c b/jdmarker.c
index f2a9cc4..2edebc2 100644
--- a/jdmarker.c
+++ b/jdmarker.c
@@ -305,7 +305,7 @@ get_sos (j_decompress_ptr cinfo)
 /* Process a SOS marker */
 {
   INT32 length;
-  int i, ci, n, c, cc;
+  int i, j, ci, n, c, cc;
   jpeg_component_info * compptr;
   INPUT_VARS(cinfo);
 
@@ -340,7 +340,11 @@ get_sos (j_decompress_ptr cinfo)
     ERREXIT1(cinfo, JERR_BAD_COMPONENT_ID, cc);
 
   id_found:
-
+    for (j = 0; j < i; j++) {
+      if (cinfo->cur_comp_info[j] == compptr) {
+        ERREXIT1(cinfo, JERR_DUP_COMPONENT_ID, cc);
+      }
+    }
     cinfo->cur_comp_info[i] = compptr;
     compptr->dc_tbl_no = (c >> 4) & 15;
     compptr->ac_tbl_no = (c     ) & 15;
@@ -480,7 +484,9 @@ get_dht (j_decompress_ptr cinfo)
       *htblptr = jpeg_alloc_huff_table((j_common_ptr) cinfo);
   
     MEMCOPY((*htblptr)->bits, bits, SIZEOF((*htblptr)->bits));
-    MEMCOPY((*htblptr)->huffval, huffval, SIZEOF((*htblptr)->huffval));
+    MEMCOPY((*htblptr)->huffval, huffval, count);
+
+    MEMZERO((*htblptr)->huffval + count, SIZEOF( (*htblptr)->huffval) - count);
   }
 
   if (length != 0)
diff --git a/jerror.h b/jerror.h
index 1cfb2b1..4007c49 100644
--- a/jerror.h
+++ b/jerror.h
@@ -77,6 +77,7 @@ JMESSAGE(JERR_DAC_INDEX, "Bogus DAC index %d")
 JMESSAGE(JERR_DAC_VALUE, "Bogus DAC value 0x%x")
 JMESSAGE(JERR_DHT_INDEX, "Bogus DHT index %d")
 JMESSAGE(JERR_DQT_INDEX, "Bogus DQT index %d")
+JMESSAGE(JERR_DUP_COMPONENT_ID, "Duplicate component ID")
 JMESSAGE(JERR_EMPTY_IMAGE, "Empty JPEG image (DNL not supported)")
 JMESSAGE(JERR_EMS_READ, "Read from EMS failed")
 JMESSAGE(JERR_EMS_WRITE, "Write to EMS failed")