A homeless man in Oklahoma was sentenced to 15 years in prison last week after police caught him with what they believed to be a bag of cocaine.

Cody Gregg, 26, pleaded guilty to drug trafficking charges following his arrest for a "traffic violation" in August. Gregg, who was riding a bike at the time, tried to flee from officers but they caught up to him and searched his belongings.

That's when police found a "large amount of white powder substance" hidden in a coffee can inside his backpack. A report from the incident said the arresting officer "believed [the powder] to be cocaine based on my training and experience."

Gregg, who had faced drug charges in the past, was booked and held in jail on a $50,000 bond. Police ran tests on the substance, which they said tested positive for cocaine.

But lab tests conducted nearly two months later said the exact opposite. By then, Gregg had already pled guilty to drug charges.

The 26-year-old then tried to withdraw his guilty plea, telling the judge the white substance was actually powdered milk he'd gotten from a local food pantry, The Oklahoman reported.

Related: Judge Rejects Man’s Request to Withdraw Guilty Plea

A judge ultimately approved Gregg's plea withdrawal, and the charges against him were dropped last Friday. He was released from prison on Monday.

Jason Lollman, a public defender in Tulsa, Okla., told NBC News that it's a common occurrence for suspects to plead guilty to crimes they didn't commit, as it saves them from having to "sit in and wait" in prison before their trial.

"The cash bail system, posting cash bail, is a problem," Lollman said. "If they can’t afford an attorney, they're not going to be able to post bond to get out."

Lollman said he's regularly had to talk clients out of falsely pleading guilty, but added that he ultimately can't blame Gregg for his decision.

"Sometimes it’s like we, the attorneys, have more stamina than the clients do," he told NBC News. "But that’s because we’re on the outside and they're in jail."

The attorney added that Oklahoma City Jail, where Gregg was being held, is a "generally awful jail." As of September, at least six inmates had died in the prison this year, The Oklahoman reported.