细分故障问题

Segmentation fault issue

本文关键字:问题 故障 细分      更新时间:2023-10-16

我正在尝试使用xdotool进行 system()命令。

以下是我的测试程序:

int main() {
    int x = 10;
    int y = 50;
    char* str;
    sprintf(str, "xdotool mousemove %d, %d", x, y);
    system(str);
}

我会得到一个分段故障(核心倾倒)错误。您是否知道允许这样的命令工作的方法?顺便说一句,我已经尝试过它。我是C 的新手,您的帮助将不胜感激。

其他答案是正确的,但是,您可以在C 中使用更好的方法,而不是使用sprintf

int main() {
   int x = 10;
   int y = 50;
   std::stringstream ss;
   ss <<  "xdotool mousemove " << x << " " << y;
   system(ss.str().c_str());
}

您的问题是您没有分配任何空间将字符串打印到。

例如,您可能想做以下操作:

int main() {
    int x = 10;
    int y = 50;
    /* this assigns 255 characters of space for the string on the stack */
    char str[255];
    /* char* str -- this assigns no space, it just defines a pointer */
    /* this function will put the format string with arguments into the
     * space you provide... It will not provide it's own space. */
    sprintf(str, "xdotool mousemove %d, %d", x, y);
    system(str);
}

这将摆脱您的SEG故障,因为您不再访问未分配的内存。

如果您不知道函数如何工作,请考虑使用C 参考指南。