Jake Badlands
Jake Badlands

Reputation: 1026

C - how to correctly use malloc'ed array with C getline function?

I want to use previously malloc'ed array with a C getline function:

ssize_t getline(char **restrict, size_t *restrict, FILE *restrict)

The following code gives me EXC_BAD_ACCESS (code=1, address=0x400) :

FILE *in; if ((in=fopen(inpath, "r+w"))==NULL) exit(1);
char * buf = (char *) malloc (BUFSIZ); // BUFSIZ is constant, equal to 1024
if (getline(&buf, (size_t *)BUFSIZ, in)<0) return 1; // <--- EXC_BAD_ACCESS

How should I modify the code to make it working?

Upvotes: 0

Views: 694

Answers (1)

cnicutar
cnicutar

Reputation: 182664

What you are doing now essentially tells getline there's a pointer to the address 1024 and you really want it to dereference it. Pass a real address as the second argument, don't cast an int and hope for the best.

size_t size = BUFSIZ;
getline(&buf, &size, in);

Upvotes: 2

Related Questions