I get the above debugging problem from the function readString. I believe it has something to do with the way ‘start’ is defined in the function. The 0x07 in the array changes depending on the length of the following string. This string should say ‘testing’ in unicode.
int main(){
char readbuffer[] = {0x07, 0x74, 0x65, 0x73, 0x74, 0x69, 0x6e, 0x67};
char *buf = readbuffer;
uint32_t *stringread = (uint32_t *) malloc(sizeof(uint32_t));
*stringread = readString(buf);
}
uint32_t readString(char *buf)
{
uint32_t *start = (uint32_t *) malloc(sizeof(uint32_t));
int len;
len = protobuf_readVarint(buf, &buf);
memcpy (&start, buf, len);
buf += len;
return start;
}
Here
you are attempting to copy the contents of
bufto&start(the address of the pointer variablestart, that is in fact an address on the stack) instead ofstart(referring to the address of the memory bufferstartis pointing to). This is what corrupts your stack.Apart from this, there are several other smaller issues in your code:
lenis > 4,memcpywill again silently write past the end of the memory block pointed to bystart, corrupting memory;you allocate a memory block within
readString()which you neverfree, leading to a memory leak; if you are absolutely sure thatlenwill never be more than 4, it would be simpler to use just a plain local variable:note that in this case it is correct to pass
&starttomemcpy!buf += lenwill have no effect outsidereadString()sincebufis passed by value, thus changes to it within the function affect only its local copy, not the original.