Help allocating and reallocating memory
Hello there, long time visitor first time poster. :D
I have a problem with the following code... it segfaults as soon as my setFT function is called. I must not be allocating the memory correctly, but what's strange is my temp self-testing code (that **(ptrtwo+5000) = 88 part) actually prints out 88 when I ask it what that particular element is. How is that possible if I haven't allocated that much memory for it?
My goal is to create a pointer to a pointer to an array of longs. Initially, the array[0] element should be this "magic number" we have. That's fine. array[1] should be the size of our "flexible table" which is initialized at 0 until the user uses setFT to add elements.
The ultimate goal is have this dynamic array of elements that allocates, deallocated, and reallocates necessary memory. I just get seg faults :(
I guess my main question(s) is why am I seg faulting, and if I'm seg faulting, how come I can still put long's into my array?! Any suggestions or thoughts would be greatly appreciated. I'm not sure how clear I have been, but if you need clarification on exactly what the heck I'm talking about, I'll try to do just that. Thank you very much!
Code:
#include <stdio.h>
#include <stdlib.h>
#include "FlexTab.h"
FlexTab newFT(){
long **ptrone;
long *ptrtwo;
ptrone = malloc(sizeof(long));
*ptrone = malloc(sizeof(long));
**ptrone = (long)calloc(2, sizeof(long));
ptrtwo = malloc(sizeof(long *));
**(ptrone) = FT_MAGIC;
ptrtwo = *ptrone;
*(ptrtwo+1) = 0;
*(ptrtwo+5000) = 88; //just a tester
printf("*(ptrtwo+1) is %ld\n", *(ptrtwo+1));
printf("**ptrone is %ld\n",**ptrone);
printf("*ptrtwo is %ld\n",*ptrtwo);
printf("Ptrtwo @ element 5000 is %ld\n", *(ptrtwo+5000)); //it works?!
return ptrone;
}
int disposeFT( FlexTab ft ){
free(*ft);
free(ft);
ft = NULL;
return 0;
}
int setFT( FlexTab ft, const int index, const long item ){
if (index > (**(ft+1)) ){
**ft = (long)realloc(*ft, (2 * sizeof(long)) + (index * sizeof(long)) );
**(ft+1) = index;
**(ft+index+2)=item;
}
else if (index < (**(ft+1)) ){
**(ft+index+2)=item;
}
return **(ft+1);
}
int getFT( FlexTab ft, const int index, long *const itemp ){
if (**ft == FT_MAGIC && *ft != NULL && ft != NULL){
*itemp = **(ft + index + 2);
return ( (sizeof(ft)) / (sizeof(long)) );
}
else if (index >= FT_MAX){
return -2;
}
return 88;
}