I was trying to figure out how the below function works, and for the most part it's coming along fine (so I guess learning about how C works along the way as well). However, I've run into an issue. On the line that has
*q = 0, chr = p, ...
If I do that in a separate, sample code, I get a segmentation fault. I know that the program that the below function is from works, and that it uses this function. I'm wondering what I'm missing. This answer seems to suggest that I'm trying to edit something I can't edit, what is the difference in the below function?
static void parse_chr(struct hk_sdict *d, char *s) // io.c 282, *d is hk_map -> d
{
char *chr, *p, *q;
int64_t len;
int has_digit, prelen;
prelen = strncmp(s, "#chromsize:", 11) == 0? 11 : 12;
for (p = s + prelen; isspace(*p) && *p != 0; ++p) {}
assert(*p);
for (q = p; *q != 0 && !isspace(*q); ++q) {}
assert(*q);
*q = 0, chr = p, p = q + 1;
// ... there is more to this function, but didn't seem relevant to the question, it manipulates the resulting p and chr from here via other functions in the program
}
A sample of text that the above function would be looking at is are lines in a text file such as:
#chromsize: chr1 249250621
#chromsize: chr10 135534747
...
Updates on s
:
s
is defined in a previous data structure as such:
typedef struct __kstring_t {
size_t l, m;
char *s;
} kstring_t
later on, a kstring_t
is initialized like so:
kstring_t str = {0,0,0};
Then later on, given an size_t value m
(which is stored in the same structure str
) we have
str->s = (char*)realloc(str->s, str->m);
This is then updated later on with (given an size_t l
, unsigned char *buf
, int begin
, int i
):
memcpy(str->s + str->l, ks->buf + ks->begin, i - ks->begin);
This is the processing done to s
, and then it is passed to the above function.
Here is my attempt (I'm not sure if all of the includes are necessary, just wanted to replicate packages which are available to the original script) (this gives me a segmentation fault (core dumped)):
#include <stdio.h>
#include <stdlib.h>
#include <errno.h>
#include <string.h>
#include <ctype.h>
#include <assert.h>
#include <zlib.h>
int main ()
{
char *s = "#chromsize: chr1 249250621";
char *p, *q, *chr;
for (p = s + 11; isspace(*p) && *p != 0; ++p) {}
assert(*p);
for (q = p; *p != 0 && !isspace(*p); ++p) {}
assert(*q);
*q = 0;
chr = p, p = q + 1;
}