LDAPRDN         *newRDN = NULL, *tmpDN_[TMP_RDN_SLOTS], **tmpDN = tmpDN_;
        int             num_slots = TMP_RDN_SLOTS;
        char            *str = bv->bv_val;
+       char            *end = str + bv->bv_len;
        
        assert( bv );
        assert( bv->bv_val );
 #endif
        }
 
-       for ( ; p[ 0 ]; p++ ) {
+       for ( ; p < end; p++ ) {
                int             err;
                struct berval   tmpbv = { bv->bv_len - ( p - str ), (char *)p };
                
                /* 
                 * We expect a rdn separator
                 */
-               if ( p[ 0 ] ) {
+               if ( p < end && p[ 0 ] ) {
                        switch ( LDAP_DN_FORMAT( flags ) ) {
                        case LDAP_DN_FORMAT_LDAPV3:
                                if ( !LDAP_DN_RDN_SEP( p[ 0 ] ) ) {
                        num_slots *= 2;
                }
                                
-               if ( p[ 0 ] == '\0' ) {
+               if ( p >= end || p[ 0 ] == '\0' ) {
                        /* 
                         * the DN is over, phew
                         */
 
                /* format of string is "entry/setAttrName" */
                if (aci_get_part(subj, 0, '/', &subjdn) < 0) {
                        return(0);
-               } else {
-                       /* FIXME: If dnNormalize was based on ldap_bv2dn
-                        * instead of ldap_str2dn and would honor the bv_len
-                        * we could skip this step and not worry about the
-                        * unterminated string.
-                        */
-                       char *s = ch_malloc(subjdn.bv_len + 1);
-                       AC_MEMCPY(s, subjdn.bv_val, subjdn.bv_len);
-                       subjdn.bv_val = s;
                }
 
                if ( aci_get_part(subj, 1, '/', &setat) < 0 ) {
                        setat.bv_val = SLAPD_ACI_SET_ATTR;
                        setat.bv_len = sizeof(SLAPD_ACI_SET_ATTR)-1;
                }
+
                if ( setat.bv_val != NULL ) {
+                       /*
+                        * NOTE: dnNormalize2 honors the ber_len field
+                        * as the length of the dn to be normalized
+                        */
                        if ( dnNormalize2(NULL, &subjdn, &ndn) == LDAP_SUCCESS
                                && slap_bv2ad(&setat, &desc, &text) == LDAP_SUCCESS )
                        {
                        if (ndn.bv_val)
                                free(ndn.bv_val);
                }
-               ch_free(subjdn.bv_val);
        }
 
        if (set.bv_val != NULL) {