I’m trying to check a in the heap with char* c = s – sizeof(unsigned);
But it always returns gibberish to me. I’m wondering what did I do wrong…
typedef
struct String {
int length;
int capacity;
unsigned check;
char ptr[0];
} String;
char* modelStrrealloc(char* myStruct, int new_capacity){
char* c = myStruct - sizeof(unsigned);
int length = strlen(s);
String *string;
if (c == 0xdeadbeef ){
printf("1st if statement");
if (*(c - sizeof(int))< new_capacity){
string = malloc(sizeof(String) + new_capacity + 1);
printf("if statement");
assert(string != 0);
(*string).length = length;
(*string).capacity = new_capacity + 1;
strcpy(string->ptr, myStruct);
(*string).check = "~0xdeadbeef";
modelStrfree(myStruct);
return string->ptr;
}
}
return myStruct;
}
IMHO, the check for
0xdeadbeefshould readand the check for capacity
The way you have it, you’re reading single characters instead of ints, and I think you didn’t intend this.
(I assume
myStructshould be a pointer to theptrstring instruct Mystruct– this is the only way it makes sense to me)Also, note that this is not really portable C, because the compiler is free to add padding to align struct members – maybe a berret approach would be to use the
offsetofmacro and get the pointer to the whole struct.