Expansion of access to effective treatments for heroin dependence is a worldwide health priority that will also reduce HIV transmission. We compared the efficacy of naltrexone, buprenorphine, and no additional treatment, in patients receiving detoxification and subsequent drug counselling, for maintenance of heroin abstinence, prevention of relapse, and reduction of HIV risk behaviours. 126 detoxified heroin-dependent patients, from an outpatient research clinic and detoxification programme in Malaysia, were randomly assigned by a computer-generated randomisation sequence to 24 weeks of manual-guided drug counselling and maintenance with naltrexone (n=43), buprenorphine (n=44), or placebo (n=39). Medications were administered on a double-blind and double-dummy basis. Primary outcomes, assessed by urine testing three times per week, were days to first heroin use, days to heroin relapse (three consecutive opioid-positive urine tests), maximum consecutive days of heroin abstinence, and reductions in HIV risk behaviours over 6 months. The study was terminated after 22 months of enrolment because buprenorphine was shown to have greater efficacy in an interim safety analysis. Analysis was by intention to treat. This study is registered with ClinicalTrials.gov, number NCT00383045. We observed consistent, linear contrasts in days to first heroin use (p=0.0009), days to heroin relapse (p=0.009), and maximum consecutive days abstinent (p=0.0007), with all results best for buprenorphine and worst for placebo. Buprenorphine was associated with greater time to first heroin use than were naltrexone (hazard ratio 1.87 [95% CI 1.21-2.88]) or placebo (2.02 [1.29-3.16]). With buprenorphine, we also recorded significantly greater time to heroin relapse (2.17 [1.38-3.42]), and maximum consecutive days abstinent than with placebo (mean days 59 [95% CI 43-76] vs 24 [13-35]; p=0.003); however, for these outcomes, differences between buprenorphine and naltrexone were not significant. Differences between naltrexone and placebo were not significant for any outcomes. HIV risk behaviours were significantly reduced from baseline across all three treatments (p=0.003), but the reductions did not differ significantly between the three groups. Our findings lend support to the widespread dissemination of maintenance treatment with buprenorphine as an effective public-health approach to reduce problems associated with heroin dependence.