Skip to content

Instantly share code, notes, and snippets.

@rah003
Last active December 3, 2018 09:35
Show Gist options
  • Save rah003/66d07a20c54f953e344361616d0ddd37 to your computer and use it in GitHub Desktop.
Save rah003/66d07a20c54f953e344361616d0ddd37 to your computer and use it in GitHub Desktop.
what is difference between notation 1) ```&(*arr[i])``` and 2) ```arr[i]``` ?
Why does 1) work and 2) fail w/ Segmentation fault?
works:
```
...
int load_arr(char *filename, struct arr_t **arr)
{
...
*arr = malloc(arr_size * sizeof(struct arr_t));
for (int i = 0; i < arr_size; i++) {
fscanf(fp,"%d %f %f", &(object.id), &(object.x), &(object.y));
init_arr(&(*arr)[i], 1);
append_arr(&(*arr)[i], object);
}
...
}
```
doesn't work (but compiles fine):
```
...
int load_arr(char *filename, struct arr_t **arr)
{
...
*arr = malloc(arr_size * sizeof(struct arr_t));
for (int i = 0; i < arr_size; i++) {
fscanf(fp,"%d %f %f", &(object.id), &(object.x), &(object.y));
init_arr(arr[i], 1);
append_arr(arr[i], object);
}
...
}
```
in version that doesn't work, it would run for first 2-3 iterations and then fail with segmentation fault 11. Valgrind would be suggesting error in init_arr or append_arr methods.
```
void init_arr(struct arr_t *c, int cap)
{
assert(c != NULL);
assert(cap >= 0);
c->size = 0;
c->capacity = cap;
c->obj = malloc(cap * sizeof(struct obj_t));
if(c->obj == NULL) {
c->capacity = 0;
}
}
void append_arr(struct arr_t *c, struct obj_t obj)
{
if(c->size >= c->capacity) {
int ns = c->capacity + ARR_CHUNK;
resize_arr(c, ns);
}
c->obj[c->size++] = obj;
}
```
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment