Question

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;
}
Was it helpful?

Solution

IMHO, the check for 0xdeadbeef should read

 if (*(unsigned*)c == 0xdeadbeef ){

and the check for capacity

  if (*(int*)(c - sizeof(int))< new_capacity){

The way you have it, you're reading single characters instead of ints, and I think you didn't intend this.

(I assume myStruct should be a pointer to the ptr string in struct 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 offsetof macro and get the pointer to the whole struct.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top