> For the complete documentation index, see [llms.txt](https://book.bsdcn.org/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://book.bsdcn.org/man/string/strdup.3.md).

# strdup.3

`strdup` — 保存字符串的副本

## 名称

`strdup`, `strdupa`, `strndup`, `strndupa`

## 库

Lb libc

## 概要

`#include <string.h>`

```c
char *
strdup(const char *str);

char *
strdupa(const char *str);

char *
strndup(const char *str, size_t len);

char *
strndupa(const char *str, size_t len);
```

## 描述

`strdup` 函数为字符串 `str` 的副本分配足够的内存，执行复制，并返回指向该副本的指针。所分配的内存使用 malloc(3) 分配，不再需要时应使用 free(3) 释放。

`strndup` 函数从字符串 `str` 中最多复制 `len` 个字符，并始终在复制的字符串末尾添加 `NUL` 终止符。

`strdupa` 函数与 `strdup` 功能相同，但使用 [alloca(3)](https://github.com/FreeBSD-Ask/freebsd-man-sc/tree/main/string/alloca.3.md) 分配内存。类似地，`strndupa` 函数与 `strndup` 功能相同，但使用 [alloca(3)](https://github.com/FreeBSD-Ask/freebsd-man-sc/tree/main/string/alloca.3.md) 分配内存。

## 返回值

若内存不足，返回 `NULL` 并将 `errno` 设置为 `ENOMEM`。否则，`strdup` 系列函数返回指向所复制字符串的指针。

## 参见

[alloca(3)](https://github.com/FreeBSD-Ask/freebsd-man-sc/tree/main/string/alloca.3.md), free(3), malloc(3), wcsdup(3)

## 标准

`strdup` 函数由 IEEE Std 1003.1-2001 ("POSIX.1") 规定。`strndup` 函数由 IEEE Std 1003.1-2008 ("POSIX.1") 规定。`strdupa` 和 `strndupa` 函数是扩展，取自 glibc。

## 历史

`strdup` 函数首次出现于 4.3BSD。`strndup` 函数在 FreeBSD 7.2 中引入。`strdupa` 和 `strndupa` 函数在 FreeBSD 15.1 中引入。


---

# Agent Instructions
This documentation is published with GitBook. GitBook is the documentation platform designed so that both humans and AI agents can read, navigate, and reason over technical content effectively. Learn more at gitbook.com.

## Querying This Documentation
If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter, and the optional `goal` query parameter:

```
GET https://book.bsdcn.org/man/string/strdup.3.md?ask=<question>&goal=<endgoal>
```

`ask` is the immediate question: it should be specific, self-contained, and written in natural language.
`goal` is optional and describes the broader end goal you are ultimately trying to accomplish on behalf of the user. GitBook uses it to tailor the answer towards what is most useful for that goal.

The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
