I am writing a framework in C and have encountered the following problem:

I need to remove the line from the structure that lies in the heap, and at the same time delete this structure, so that only the line remains:

char* _EndStr(void* self) { struct c_class* this = self; char* _proxy = this->inStr; this->inStr = NULL; free(this); // знаю, что не хорошая практика, но по-другому никак не смог спроектировать return _proxy; } 

this->inStr is of type char* and was initialized as this->inStr = malloc(...); , but after passing to _proxy I cannot use free(_proxy) . Why it happens?

If I remember correctly, the memory size is written in front of the pointer, which malloc gives out, that is, when it is reassigned, this size should remain and free () should work.

simpler code to reproduce the problem:

 char* m = malloc(sizeof(int)); strcpy(m, "abcd"); char* r = m; m = NULL; free(r); 

Closed due to the fact that off-topic participants AnT , 0xdb , freim , aleksandr barakin , meine 21 Apr at 9:32 .

It seems that this question does not correspond to the subject of the site. Those who voted to close it indicated the following reason:

  • "The question is caused by a problem that is no longer reproduced or typed . Although similar questions may be relevant on this site, solving this question is unlikely to help future visitors. You can usually avoid similar questions by writing and researching a minimum program to reproduce the problem before publishing the question. " - AnT, 0xdb, freim, aleksandr barakin, meine
If the question can be reformulated according to the rules set out in the certificate , edit it .

  • “A simpler code to reproduce the problem” personally works perfectly for me - andreymal
  • (not counting going out of the buffer in strcpy, of course, but it did not affect the performance) - andreymal
  • HEAP CORRUPTION DETECTED: after Normal block (# 87) at 0x00000239145213E0. CRT detected heap buffer. I write this, there is nothing except the code above - Ilya Pakhmutov
  • Well, it's just going beyond the buffer, malloc(5) use - andreymal
  • thank you, really, there was a mistake in this - Ilya Pakhmutov

1 answer 1

It just means that your program has undefined behavior.

For example, even this code snippet

 char* m = malloc(sizeof(int)); strcpy(m, "abcd"); char* r = m; m = NULL; free(r); 

incorrect, because the strcpy function overwrites memory outside of the dynamically allocated memory (assuming that sizeof( int ) not greater than 4 ), whose address is stored in the variable m , as it is still trying to copy the trailing zero of the string literal.

It would be correct to write, for example,

 #include <stdio.h> #include <string.h> #include <stdlib.h> int main(void) { char *m = malloc( sizeof( int ) ); strncpy( m, "abcd", sizeof( int ) ); char *r = m; m = NULL; printf( "%*.*s\n", ( int )sizeof( int ), ( int )sizeof( int ), r ); free(r); }