对c中指针的操作

时间:2016-10-06 23:37:25

标签: c pointers

为什么这个代码不起作用,在我的linux VPS内存泄漏的在线编译器返回段故障...

#include <ctype.h>
#include <stdio.h>
#include <string.h>
char *a_foo(char *str) {
    unsigned char *p = (unsigned char *)str;

    while (*p) {
        *p = 'a';
        p++;
    }
    return str;
}

int main() {
    char * test = "TestTest";
    a_foo(test);
    printf("result: %s\n", test);
}

在线编译器:LINK

1 个答案:

答案 0 :(得分:2)

字符串文字"TestTest"可能存储在您环境中的只读内存中,因此尝试写入它的a_foo中的代码将失败。

字符串文字的类型具有const限定符,如果您尝试将其分配给非常量指针变量,编译器应警告您。