The S&P 500 and the Nasdaq fell on Tuesday as investors booked profits following the stock market's recent run-up, while a weaker-than-expected reading on a measure of consumer confidence sparked caution about the recovery of spending.

Technology and consumer discretionary shares fared worse than the broader market as investors sold recent winners. Baidu Inc's disappointing outlook added to the negative tone for tech names. The semiconductor index <.SOXX> shed 2.5 percent.

Even so, the Dow Jones industrial average <.DJI> eked out a slim gain as shares of Exxon Mobil and Chevron , both set to report quarterly results later this week, rose on the back of BP Plc's strong earnings.

The day's declines marked the third straight day of losses for the S&P 500 and the Nasdaq.

People want to take some profits. The consumer confidence numbers weren't great, said Stephen Carl, principal and head of U.S. equity trading at The Williams Capital Group LP in New York. We had a good run with the Dow topping around 10,000 over the last week. Many people feel the market could be overvalued.

The Dow Jones industrial average <.DJI> gained 14.21 points, or 0.14 percent, to 9,882.17. The Standard & Poor's 500 Index <.SPX> fell 3.54 points, or 0.33 percent, to 1,063.41. The Nasdaq Composite Index <.IXIC> declined 25.76 points, or 1.20 percent, to 2,116.09.

International Business Machines Corp gave the Dow an additional prop by announcing an increase in its stock-buyback plan to $9.2 billion. IBM shares rose 0.5 percent to $120.65.

The S&P 500 is now up 57.2 percent from the 12-year closing low of March 9, having slipped from its recovery peak when it was up 62.3 percent from that significant low.

Baidu, the Chinese Web Search company's stock, down 11.4 percent at $383.66, was the second-worst drag on the Nasdaq, behind Apple Inc , which fell 2.5 percent to $197.37.

Shares of Google Inc , the world's leading Web Search company, declined 1.1 percent to $548.29, a day after Baidu forecast a sequential decline in fourth-quarter revenue.

But Exxon Mobil shares shot up 2.3 percent to $74.91, while Chevron shares climbed 1.5 percent to $76.59 following BP's results. The energy sector also got a boost from a bounce in crude oil prices.

On the New York Mercantile Exchange, December crude ended up 87 cents, or 1.11 percent, at $79.55 a barrel.

On the economic front, the Conference Board's index of consumer confidence fell to 47.7 in October, weaker than economists had forecast. The data showed consumers were increasingly concerned about job market conditions.

The S&P retail index <.RLX> fell 1.6 percent and the S&P consumer discretionaries index <.GSPD> dropped 1.7 percent.

Other data showed home prices rose for the fourth-straight month in August. The Standard & Poor's/Case-Shiller composite index of home prices in 20 metropolitan areas rose more than expected in August.

(Editing by Jan Paschal)