【问题标题】:system() changes char* argument address in a function in Csystem() 更改 C 函数中的 char* 参数地址
【发布时间】:2019-05-24 16:15:22
【问题描述】:

我有功能,说:

int foo(char* a)
{
    printf("%d\n", (int)a);
    char cmd[] = "echo hello";
    system(cmd);
    printf("%d\n", (int)a);
}

在 C 代码中,然后我在 linux 上运行它;这样做之后,我看到 printf 输出是:

274351760
1853775725

我只是很困惑!任何想法?! :|

【问题讨论】:

  • char cmd[] = "echo hello";
  • @wildplasser 不工作!
  • 你怎么称呼 foo?
  • @JohnSibly 这只是我庞大代码的抽象部分!调用这个函数有一些回溯,但我确信在调用 system() 之前a 的值是有效的,但在调用之后它不是!
  • 预编辑问题中描述的行为清楚地表明char cmd[10] = "echo hello";中的空字符终止符空间不足导致了问题或程序中的其他地方存在问题(即, 显示的代码片段不是问题的根源;其他原因正在破坏内存或以其他方式破坏程序)。

标签: c system


【解决方案1】:

在这里工作:


#include <stdio.h>
#include <stdlib.h>

int foo(char* a)
{
    printf("%p\n", a);
    char cmd[] = "echo hello";
    system(cmd);
    printf("%p\n", a);
        return 0;
}

int main(void)
{
foo("OMG");
return 0;
}

输出:


$ ./a.out
0x400718
hello
0x400718

【讨论】:

    猜你喜欢
    • 2016-04-03
    • 1970-01-01
    • 1970-01-01
    • 2013-03-10
    • 2021-09-06
    • 2013-01-02
    • 2014-05-21
    • 2012-05-27
    • 1970-01-01
    相关资源
    最近更新 更多