arrays - C: Stack implementation of malloc and free -
i reading k&r pointers section 5.4 stack implementation of malloc() , free() done. using gdb debug code, , alloc() part working expected. afree() part, pointers still pointing same location before. here code :
#include <stdio.h> #define allocsize 10000 static char allocbuf[allocsize]; static char* allocp = allocbuf; char* alloc(int n) { if(allocbuf + allocsize - allocp >= n) { allocp += n; return (allocp - n); } else return 0; } void afree(char* p) { if(p >= allocbuf && p < allocbuf + allocsize) allocp = p; } int main() { char* = alloc(10); = "ayushnair"; char*b = alloc(5); b = "snea"; printf("%p %p\n", a, b); afree(b); afree(a); printf("%p %p\n", a, b); return 0; } new allocation
allocp 0x601080
after char* = alloc(10);
allocp 0x60108a
after char* b = alloc(5);
allocp 0x60108f
after afree(b);
allocp 0x60108f
after afree(a);
allocp 0x60108f
allocp still points 0x60108f. why not update according code?
in code, saying
a = "ayushnair"; you're not storing "ayushnair" into memory pointed a. "ayushnair" string literal , saying
a = "ayushnair"; you're storing base address of string literal a. way, you're overwriting returned pointer call alloc().
this not want. may need use strcpy() copy string literal into returned pointer.
that said, per current code, later calling
afree(b); afree(a); you're invoking undefined behavior you're trying comapre pointers not point same object.
quoting c11, chapter §6.5.8, relational operators
when 2 pointers compared, result depends on relative locations in address space of objects pointed to. if 2 pointers object types both point same object, or both point 1 past last element of same array object, compare equal. if objects pointed members of same aggregate object, pointers structure members declared later compare greater pointers members declared earlier in structure, , pointers array elements larger subscript values compare greater pointers elements of same array lower subscript values. pointers members of same union object compare equal. if expression p points element of array object , expression q points last element of same array object, pointer expression q+1 compares greater p. in other cases, behavior undefined.
Comments
Post a Comment