为什么我的fprintf无法将stdout作为流传递?

时间:2016-03-15 10:29:11

标签: c

我有以下功能:

void print_out_str(FILE* outstream, UINT x, int n) {

   assert(n >= 1);

   int n1, n2, j;

   n1 = (n - 1)/64; n2 = n % 64;
   for(j = 0; j <= n1 - 1; j++) 
      fprintf(outstream,"%016llx ",x[j]); //padding with 0
   fprintf(outstream,"%016llx ",x[n1] & ((1ULL<<n2) - 1ULL));

其中“outstream”是我要打印的位置,UINTuint64_t*的typedef,而n是我要打印的位数。

我不明白为什么但每次尝试调用此类函数时,程序都会因为分段错误而崩溃。我已经尝试使用GDB来理解变量内容(outstream, x, n)是否符合我的预期,并且没问题。具体来说,我尝试使用两个元素的数组,n = 87和x [0] = x [1] = 0,outstream = stdout。

我错过了什么吗?

更新:

更多信息......

这是我在提到的函数之前调用的代码:

void test_set_bit() {
   int nbits_to_allocate, i;
   UINT x;

   printf("Set the size of your x var: "); scanf("%d",&nbits_to_allocate);
   init_ui(x,nbits_to_allocate);
   printf("Set the specific bit would you like to set: "); scanf("%d",&i);

   set_ui_zero(x,nbits_to_allocate);
   printf("Content before the bit set:\n");
   print_out_str(stderr,x,nbits_to_allocate);
   //Neglect the following three lines...
   //set_ui_bit(x,nbits_to_allocate,i); 
   //printf("Content after the bit set:\n");
   //print_out_str(stderr,x,nbits_to_allocate);

}

其中init_ui

void init_ui(UINT x, int n) {

   assert(n >= 1);

   int N;
   N = (n + 63)/64;
   x = (UINT)malloc(N*sizeof(uint64_t));
}

1 个答案:

答案 0 :(得分:5)

在C中,函数参数是通过值传递,在callee中修改它们不会影响调用者的局部变量。您使用具有自动存储持续时间的未初始化变量x的值来调用未定义行为,这是不确定的。

使用指针让调用者修改调用者的局部变量。

void init_ui(UINT *x, int n) { /* add * to declare pointer to UINT */

   assert(n >= 1);

   int N;
   N = (n + 63)/64;
   *x = malloc(N*sizeof(uint64_t)); /* add * to access what is pointed by x */
}

用法:

UINT x;

init_ui(&x,nbits_to_allocate); /* add & to get address of x */
相关问题