c - 指针所在的堆栈

标签 c

我在 APUE 中阅读了 make_tempory_file 演示,并对以下内容感到困惑:

char good_template[] = "/tmp/dirXXXXXX"; /* right way */
char *bad_template = "/tmp/dirXXXXXX"; /* wrong way*/

void make_temp(char *template);

int main()
{
    char  good_template[] = "/tmp/dirXXXXXX"; /* right way */
    char  *bad_template = "/tmp/dirXXXXXX"; /* wrong way*/

    printf("trying to create first temp file...\n");
    make_temp(good_template);
    printf("trying to create second temp file...\n");
    make_temp(bad_template);
    exit(0);
}

void make_temp(char *template)
{
    int fd;
    struct stat sbuf;

    if ((fd = mkstemp(template)) < 0)

        err_sys("can’t create temp file");
    printf("temp name = %s\n", template);
    close(fd);
    if (stat(template, &sbuf) < 0)
    {
        if (errno == ENOENT)

            printf("file doesn’t exist\n");
        else
            err_sys("stat failed");
    }
    else
    {
        printf("file exists\n");
        unlink(template);
    }
}

指令解释:

The difference in behavior comes from the way the two template strings are declared. For the first template, the name is allocated on the stack, because we use an array variable. For the second name, however, we use a pointer. In this case, only the memory for the pointer itself resides on the stack; the compiler arranges for the string to be stored in the read-only segment of the executable. When the mkstemp function tries to modify the string, a segmentation fault occurs.

我试图理解这个陈述,但坚持 stack

它指的是箭头所指的堆栈吗?

enter image description here

最佳答案

When the mkstemp function tries to modify the string, a segmentation fault occurs.

原因是因为字符串声明为char *bad_template = "/tmp/dirXXXXXX"; bad_template被分配给字符串文字

C ,修改字符串文字是未定义的行为

引用 - C99 标准第 6.4.5-6 节

A character string literal is a sequence of zero or more multibyte characters enclosed in double-quotes, as in "xyz". A wide string literal is the same, except prefixed by the letter L.

If the program attempts to modify such an array, the behavior is undefined.

关于c - 指针所在的堆栈,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53293205/

相关文章:

c - 为什么这个小程序输出True? GCC有溢出保护吗?

c - 在c中表示 float

c - 我为 C 编程作业创建的 system.h 文件是否有可能给我的操作系统带来问题?

c - 这个 switch case 语法是什么意思?

c++ - 如何关闭线程(pthread 库)?

c - 有没有一种简单的方法可以从文件中使用 SDL 创建字符串?

c - 程序不会提示用户最后一次输入,而是循环第二本书 - 数据结构

c++ - 如何在用户空间使用bitops.h

c - linux 内核的 ext2 函数 ext2_statfs() 中的内存屏障

c - 凯撒密码的实现有什么问题?