在函数中更改指针的值

标签 c pointers valgrind

我想在函数中更改变量的值。 我的代码是这样的:

void change(char *buf){
    char str = "xxxxxxx";
    *buf = &str;
}
int main(){
    char *xxx = NULL;
    change(xxx);
}

当我用 valgrind 调试时,它说:

==3709== Invalid write of size 1
==3709==    at 0x80483CA: change (test.c:5)
==3709==    by 0x80483E5: main (test.c:10)
==3709==  Address 0x0 is not stack'd, malloc'd or (recently) free'd
==3709== 
==3709== 
==3709== Process terminating with default action of signal 11 (SIGSEGV)
==3709==  Access not within mapped region at address 0x0
==3709==    at 0x80483CA: change (test.c:5)
==3709==    by 0x80483E5: main (test.c:10)

谁能帮帮我?我是 C 的新手....

最佳答案

使用指向指针的指针:

void change(char **buf)
{
    *buf = "xxxxxxx";
}

int main(void)
{
    char *xxx = NULL;
    change(&xxx);
}

关于在函数中更改指针的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12451176/

相关文章:

c++ - pow(x,3.0f) 与 x*x*x 的性能对比?

c - 为什么编译器不能插入代码来检测缓冲区溢出?

不使用 libelf 或其他库创建 ELF 二进制文件

c++ - C++ 中的析构函数和类 [内存泄漏]

c - 错误 : Conditional jump or move depends on uninitialised value - C valgrind

c - 如何在 Linux 上正确地将网络接口(interface)置于混杂模式

c++ - 内存分配崩溃

c - C 中指针的声明和初始化

c - 使用结构体在函数之间传递数组信息

c++ - 来自boost::asio的Valgrind错误