C&C++   发布时间:2022-04-03  发布网站:大佬教程  code.js-code.com
大佬教程收集整理的这篇文章主要介绍了C中的system()时出现分段错误大佬教程大佬觉得挺不错的,现在分享给大家,也给大家做个参考。
我想使用 linux的“base64”脚本对数据进行编码并在C中获取.
当我尝试编译 @H_502_8@

@H_502_8@

char a[200];
strcpy(a,"Hello");
printf("%s",a);
@H_502_8@我得到了输出

@H_502_8@

Hello
@H_502_8@现在,每当我尝试代码

@H_502_8@

char a[200];
strcpy(a,system("echo Hello | base64"));
printf("%s",a);
@H_502_8@我得到了输出

@H_502_8@

aGVsbG8K
Segmentation fault
@H_502_8@即使我删除了“printf”语句,我也是如此

@H_502_8@

aGVsbG8K
Segmentation fault
@H_502_8@我想保存输出的值

@H_502_8@

system("echo Hello | base64")
@H_502_8@在’a’而不显示它.请帮忙

解决方法

这里 @H_502_8@

@H_502_8@

strcpy(a,system("echo Hello | base64"));
@H_502_8@system()不会将其结果存储到数组a中,因为System()作业是执行参数&中提供的命令.将它打印在控制台上,即stdout缓冲区.从system的手册页

@H_502_8@

@H_502_8@有一种方法可以解决这个问题,即不是在stdout上打印system()输出,而是可以将其输出重定向文件&然后从文件&中读取打印.例如

@H_502_8@

int main(void) {
        close(1); /* stdout file descriptor is avilable Now */
        /* create the file if Doesn't exist,if exist truncate the content to 0 length */
        int fd = open("data.txt",O_CREAT|O_TRUNC|O_RDWR,0664); /* fd gets assigned with loWest 
                                                  available fd i.e 1 i.e NowonWARDs stdout output 
                                                  gets rediredcted to file */
        if(fd == -1) {
                /* @TODO error handling */
                return 0;
        }
        system("echo Hello | base64"); /* system output gets stored in file */
        int max_char = lseek(fd,2);/* make fd to point to end,get the max no of char */
        char *a = malloc(max_char + 1); /* to avoid buffer overflow or 
                underflow,allocate memory only equal to the max no of char in file */
        if(a == NULL) {
                /* @TODO error handling if malloc fails */
                return 0;
        }
        lseek(fd,0);/* from beginning of file */
        int ret = read(fd,a,max_char);/* Now read out put of system() from
                                          file as array and print it */
        if(ret == -1) {
                /* @TODO error handling */
                return 0;
        }
        a[ret] = '\0';/* \0 terminated array */
        dup2(0,fd);/*fd 0 duplicated to file descriptor where fd points i.e */
        printf("output : %s \n",a);
        /* to avoid memory leak,free the dynamic memory */
        free(a);
        return 0;
}
@H_502_8@我的上述建议是一个临时修复&我不会推荐这个,而是按照@chris Turner(http://man7.org/linux/man-pages/man3/popen.3.html)的建议使用[popen]

@H_502_8@

@H_502_8@例如

@H_502_8@

int main(void) {
        char buf[1024];
        FILE *fp = popen("echo Hello | base64","r");
        printf("%s\n",fgets(buf,sizeof(buf),fp));
        return 0;
}

大佬总结

以上是大佬教程为你收集整理的C中的system()时出现分段错误全部内容,希望文章能够帮你解决C中的system()时出现分段错误所遇到的程序开发问题。

如果觉得大佬教程网站内容还不错,欢迎将大佬教程推荐给程序员好友。

本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。