vs2019 _alloca
时间: 2023-09-10 19:12:50 浏览: 168
_alloca是一种在栈上动态分配内存的函数,在VS2019中仍然存在。它的作用类似于malloc函数,但是分配的内存空间在函数返回时自动被释放。需要注意的是,由于_alloca是在栈上分配内存,因此分配的空间大小应该谨慎考虑,以免造成栈溢出等问题。此外,_alloca函数在标准C中并不存在,是Windows平台特有的函数。
相关问题
注释此函数,int get_process_comm(pid_t pid, char **ret) { _cleanup_free_ char *escaped = NULL, *comm = NULL; int r; assert(ret); assert(pid >= 0); if (pid == 0 || pid == getpid_cached()) { comm = new0(char, TASK_COMM_LEN + 1); /* Must fit in 16 byte according to prctl(2) */ if (!comm) return -ENOMEM; if (prctl(PR_GET_NAME, comm) < 0) return -errno; } else { const char *p; p = procfs_file_alloca(pid, "comm"); /* Note that process names of kernel threads can be much longer than TASK_COMM_LEN */ r = read_one_line_file(p, &comm); if (r == -ENOENT) return -ESRCH; if (r < 0) return r; } escaped = new(char, COMM_MAX_LEN); if (!escaped) return -ENOMEM; /* Escape unprintable characters, just in case, but don't grow the string beyond the underlying size */ cellescape(escaped, COMM_MAX_LEN, comm); *ret = TAKE_PTR(escaped); return 0; }
```
/*
* This function retrieves the name of the process associated with a given PID.
* The name is returned in the ret parameter.
*
* Parameters:
* pid - process ID to look up
* ret - pointer to a char pointer that will be set to the process name
*
* Returns:
* 0 on success
* negative error code on failure
*/
int get_process_comm(pid_t pid, char **ret) {
_cleanup_free_ char *escaped = NULL, *comm = NULL;
int r;
assert(ret);
assert(pid >= 0);
if (pid == 0 || pid == getpid_cached()) {
/* If the PID is 0 (kernel process) or matches the current process, get the current process name using prctl */
comm = new0(char, TASK_COMM_LEN + 1); /* Must fit in 16 bytes according to prctl(2) */
if (!comm)
return -ENOMEM;
if (prctl(PR_GET_NAME, comm) < 0)
return -errno;
} else {
/* Otherwise, read the process name from the /proc filesystem */
const char *p;
p = procfs_file_alloca(pid, "comm");
/* Note that process names of kernel threads can be much longer than TASK_COMM_LEN */
r = read_one_line_file(p, &comm);
if (r == -ENOENT)
return -ESRCH;
if (r < 0)
return r;
}
/* Escape unprintable characters, just in case, but don't grow the string beyond the underlying size */
escaped = new(char, COMM_MAX_LEN);
if (!escaped)
return -ENOMEM;
cellescape(escaped, COMM_MAX_LEN, comm);
*ret = TAKE_PTR(escaped);
return 0;
}
```
这是一个获取指定PID进程名称的函数。如果PID为0或与当前进程匹配,则使用prctl获取当前进程名称。否则,从/proc文件系统中读取进程名称。函数将返回名称,并对名称进行转义以避免不可打印字符。
alloca怎么获取内存
`alloca()` 函数是用来在栈上分配内存的,其原型为 `void *alloca(size_t size)`,它接受一个 `size` 参数,表示要分配的内存大小,单位为字节。`alloca()` 函数会在栈上分配一块连续的内存空间,并返回一个指向该内存空间起始地址的指针。使用 `alloca()` 函数分配的内存空间会随着函数的返回而自动释放,无需手动释放。
下面是一个使用 `alloca()` 函数分配内存的示例:
```c
#include <stdio.h>
#include <alloca.h>
int main() {
char *str;
str = alloca(10);
sprintf(str, "hello");
printf("%s\n", str);
return 0;
}
```
在上面的示例中,我们使用 `alloca()` 函数分配了一块大小为 10 字节的内存空间,然后将字符串 "hello" 写入该内存空间,并输出该字符串。注意,使用 `alloca()` 函数分配的内存空间不能使用 `free()` 函数释放,否则会导致程序崩溃。
阅读全文