samedi 28 février 2015

Pointer to pointer allocation then iteration causes segmentation fault


I'm having issues with the following code. I'm pretty sure it's correct. I'm trying to allocate memory to a pointer in a function, then write data to the allocated memory in that same function with a for loop. But when the counter reaches 2 on the for loop, it causes a segmentation fault, or I try to set a bunch of values in a loop or read from it.


Yes, I have researched this on StackOverflow, but I didn't find the following answers too helpful. * How can I allocate memory and return it (via a pointer-parameter) to the calling function?



#include <cassert>
#include <cstdlib>
#include <cstdio>

typedef unsigned char uint8_t;

void allocMem(uint8_t **i){
*i = new uint8_t[10];
for(int j = 0; j < 10; j++){
printf("%d\n", *i[j]);
//*i[j] = j * 2;
}
}

int main(){
uint8_t *i = 0;
allocMem(&i);
assert(i != NULL);
delete[] i;
}



Aucun commentaire:

Enregistrer un commentaire