c - Return argument doesn't work — gives me weird error -
this simple program should create substring string, should return substring can printed out. it's exercise , substring function can changed. problem can't find return type doesn't spark kinds of warnings , errors.
how should change return type?
static void panic(const char *serror) { printf("%s", serror); exit(1); } static void *xmalloc(size_t size) { void *ptr; if (size == 0) panic("size 0!\n"); ptr = malloc(size); if (!ptr) panic("no mem left!\n"); return ptr; } static char *substring(const char *str, off_t pos, size_t len) { char out [len]; int index; for(index = 0; index < (pos + len); index++) { if(index >= pos && index < (pos + len)) { out[index - pos] = str[index]; } } return out; } int main(int argc, char **argv) { char *foo = "nicht\n"; char *bar = substring(foo, 2, 3); printf("%s", bar); free(bar); return 0; }
you invoked 2 undefine behavior by
- dereferencing pointer
bar
points @ vanished local variable. - passing non-
null
pointer doesn't point @ buffer allocated viamalloc()
,calloc()
orrealloc()
.
also note that
- you have terminate string adding null character.
- your loop not efficient.
corrected code:
static char *substring(const char *str, off_t pos, size_t len) { char *out = xmalloc(len + 1); int index; for(index = pos; index < (pos + len); index++) { out[index - pos] = str[index]; } out[len] = '\0'; return out; }
Comments
Post a Comment