这个 C 程序安全吗?

Is this C program safe?

我担心此程序中的内存泄漏。具体来说,check_if_pal 过程递增 str 指针以隐藏第一个字符。这会干扰自动内存分配吗?使用堆会更安全吗?我需要在返回前恢复 str 吗?

这是代码:

# include <stdio.h>
# include <string.h>

int check_if_pal(char *);

int main(int argc, char *argv[]) {

        char *not;

        for (int i = 1; i < argc; i++) {
                if (check_if_pal(argv[i])) {
                        not = " not";
                } else {
                        not = "";
                }

                printf("%s is%s a palindrome.\n", argv[i], not);
        }

        return 0;
}

int check_if_pal(char *str) {

        while (strlen(str) > 1) {
                if (str[0] != str[strlen(str) - 1]) {
                        return 0;
                }

                str[strlen(str) - 1] = '[=10=]';
                str++;
        }

        return 1;
};

这里没有分配任何东西,所以不会有任何内存泄漏。

即使您有分配,请记住指针并不代表分配 per-se,它指向分配的内存 并且最终 free() 它。如果你忘记了指针,如果你改变指针,它不会使分配无效。

您可以根据需要随意更改像 str 这样的参数指针,因为这只会影响该函数的局部范围。

Is this C program safe?

由于您如何操纵 str 指针,因此很难分析。证明程序是 memory-safe 可能非常容易或非常困难,具体取决于代码的编写方式。

例如,尝试只调用 strlen 一次并保持 str 不变。这样你会发现证明索引保持在范围内要容易得多。

I am concerned about memory leaks in this program.

没有内存泄漏,因为没有分配。

Specifically, the check_if_pal procedure increments the str pointer to hide the first character. Will this interfere with automatic memory allocation?

不,不会。

Would it be safer to use the heap?

这取决于环境、操作系统、编译器、使用的标志...

不过,一般来说,堆可能更容易发现错误(尤其是在调试时),因为分配更加明确。

Do I need to restore str before returning?

不,指针是一个副本,所以你可以做任何你想做的事情。