Locke is coming off a rough season that saw him get released by the Indianapolis Colts and later the Detroit Lions after he appeared in five games for the Lions.
With Detroit, Locke punted 27 times for 1,222 yards, giving him an average of 45.3 yards.
Locke was a fifth-round pick of the Minnesota Vikings out of UCLA in 2013. In 64 games over four seasons for Minnesota, he registered 290 punts for 12,535 yards, an average 43.2 yards.
Besides announcing the signing of Locke, the 49ers also announced running back Raheem Mostert signed his one-year exclusive rights tender.
Mostert was tendered a one-year contract as an exclusive rights free agent on Friday. He appeared in the 49ers' first 11 games of 2017 and finished with six carries for 30 yards while adding eight tackles on special teams.
Before joining the 49ers in 2016, Mostert appeared in games for the Chicago Bears, Cleveland Browns, Baltimore Ravens and Miami Dolphins.