1

I have the following code -

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

typedef unsigned char Byte;

typedef struct _big_num {
   int  nbytes;  // size of array
   Byte *bytes;  /// array of Bytes
} BigNum;

void initBigNum(BigNum *n, int Nbytes)
{
    n = malloc(sizeof(BigNum));
    assert(n != NULL);
    n->bytes = calloc(Nbytes, sizeof(char));
    assert(n->bytes != NULL);
    if (n -> bytes == NULL) {
        fprintf(stderr, "error\n");
    }
    n->nbytes = Nbytes;
    return;
}

int main() {

    BigNum num1;
    BigNum num2;

    initBigNum(&num1, 20);
    initBigNum(&num2, 20);

    if (num1.bytes == NULL) {
        fprintf(stderr, "num1->bytes is NULL\n");
    }

    if (num2.bytes == NULL) {
        fprintf(stderr, "num2->bytes is NULL\n");
    }

    return 0;
}

I compile using gcc -std=c99 -Wall aa.c. I am using MacOS.

The output is num2->bytes is NULL.

Why only the num2 part is shown NULL? Why not num1? I tried searching online for it, but I am not sure how should I search for it.

For context, I was trying to design a small BigInt library in C for a project. However, I am stuck as the second num2 always throw seg fault when I try to use it in strncpy.

I reproduced the same thing in the shortest code above.

arfat
  • 171
  • 1
  • 8

0 Answers0