【问题标题】:Segmentation fault after SYSTEM call executionSYSTEM调用执行后的分段错误
【发布时间】:2013-08-29 09:16:06
【问题描述】:

请告诉我我在做什么是对还是错。如果它是正确的,那么为什么我会遇到分段错误?

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

char* EncodeToBase64(char*);

int main()
{
    char str[24] = {0};
    char *output = NULL;
    output = malloc(56*sizeof(char));
    scanf("%[^\n]s",str);
    output = EncodeToBase64(str);
    printf("Back %s",*output);
    return 0;
}

char* EncodeToBase64(char *str)
{
    char buff[24];
    char *output = NULL;
    output = malloc(56*sizeof(char));
    memset(buff,'0',sizeof(buff));
    printf("EncodeToBase64 Function\n");
    sprintf(buff,"echo %s | openssl enc -base64",str);
    printf("%s\n",buff);
    output = system(buff);
    printf("Back %s",*output);

    return output;
}

更正我的代码后,我又遇到了一个问题,每次我将这三个字符附加到我的字符串ô/+...如何获得准确的字符串?

【问题讨论】:

  • 对于每个malloc(),都应该有一个free()

标签: c segmentation-fault


【解决方案1】:

system() 返回一个int,这是进程的退出状态,而不是标准输出。 因此将system() 的返回值分配给char * 并打印 没有任何意义。

您可以使用popen() 启动进程并读取其输出。

示例(使用固定大小的缓冲区,为简洁起见不检查错误):

char * EncodeToBase64(char *str)
{
    char buff[1024], output[1024];

    snprintf(buff, sizeof(buff), "echo %s | openssl enc -base64", str);
    FILE *fp = popen(buff, "r");
    size_t amount = fread(output, 1, sizeof(output) - 1, fp);
    output[amount] = 0; // zero terminate string
    fclose(fp);

    return strdup(output);
}

用法:

char *b64 = EncodeToBase64("Hello world");
printf("%s", b64);
free(b64);
// Output: SGVsbG8gd29ybGQK

【讨论】:

  • 我可以使用system 作为popen 的参数吗? popen(system,"r");?
  • @Krishna:popen() 的第一个参数与 system() 参数相同,所以 FILE *fp = popen(buff, "r") 在你的情况下。
  • 但我仍然没有在我的主函数中得到这个输出。
  • @Krishna 这个答案是正确的,但 sr01853 的答案也是如此。您的代码存在很多问题,以至于没有一个答案可以完全涵盖它们。当你变成一个帮助吸血鬼时,你需要做更多的研究。
  • @trojanfoe...我弄错了...感谢您的帮助...还有一个问题,每次我将这三个字符附加到我的字符串ô/+...如何得到确切的字符串?
【解决方案2】:
printf("Back %s",output);

打印字符串时,output 是参数

freemalloc'ed 的内存是一个很好的做法

我认为main() 中的malloc 是不必要的。

【讨论】:

  • @Krishna:你纠正了printf()ing *output两个出现吗?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-03-17
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-04-27
  • 1970-01-01
相关资源
最近更新 更多