Reputation: 428
when i run this i get segv on printf, what am i doing wrong?
int main() {
char **bla;
int size =10;
int i;
bla = calloc(size*size,sizeof(char *));
for(i=0;i<size;i++) {
*bla = calloc(10,sizeof(char));
strncpy(*bla,"aaaaa",size);
bla++;
}
printf("%s\n",bla[0]);
}
I know i could do this with
int main() {
char **bla;
int size =10;
int i;
bla = calloc(size*size,sizeof(char *));
for(i=0;i<size;i++) {
bla[i] = calloc(10,sizeof(char));
strncpy(bla[i],"aaaaa",size);
}
printf("%s\n",bla[0]);
}
but is there any way to do this with pointers?
Upvotes: 1
Views: 162
Reputation: 7477
The problem is that in the first case you've moved the bla pointer past the end of the array (the last bla++) so when you access the first you are actually accessing past the last
Upvotes: 0
Reputation: 126203
The problem is that your allocation loop uses bla
to iterate through the array of pointers, so at the end of that loop, bla
points to just after the end of the array rather than the beginning. You need a loop like:
for (p=bla; p < bla+size; p++) {
*p = calloc(size, sizeof(char));
strncpy(*p, "aaaaa", size);
}
Upvotes: 1
Reputation: 887453
By writing bla++
, you're changing bla
to point to the next pointer.
At the end, bla[0]
(which is equivalent to *bla
) has been incremented 10 times and will point the memory location immediately after the allocated block.
You could fix this by writing bla -= 10
after the loop.
However, the best way to fix it is to not increment bla
at all, and instead write
*(bla + i) = calloc(10,sizeof(char));
Alternatively, you could declare a second pointer (char** currentBlah = blah
) and increment it instead, then print blah[0]
, which will still point to the original memory location.
Upvotes: 5