Quantcast
Channel: Active questions tagged gcc - Stack Overflow
Viewing all articles
Browse latest Browse all 22289

How realloc works passed 0 size as argument

$
0
0

How realloc works passed 0 size as argument?

from man page:Unless ptr is NULL, it must havebeen returned by an earlier call to malloc(), calloc(), or realloc().

Why it needs to be?

compile this with gcc (Ubuntu 9.4.0-1ubuntu1~20.04.2) 9.4.0 with no options(flags)

this sample

#include <stdlib.h>int main () {    int *p = malloc(0);    p = realloc(p, 0);    return 0;}

this is working code, checking memory with valgrind show this:

valgrind --leak-check=full --show-leak-kinds=all --track-origins=yes ./test==185872== Memcheck, a memory error detector==185872== Copyright (C) 2002-2017, and GNU GPL'd, by Julian Seward et al.==185872== Using Valgrind-3.15.0 and LibVEX; rerun with -h for copyright info==185872== Command: ./test==185872== ==185872== ==185872== HEAP SUMMARY:==185872==     in use at exit: 0 bytes in 0 blocks==185872==   total heap usage: 1 allocs, 1 frees, 0 bytes allocated==185872== ==185872== All heap blocks were freed -- no leaks are possible==185872== ==185872== For lists of detected and suppressed errors, rerun with: -s==185872== ERROR SUMMARY: 0 errors from 0 contexts (suppressed: 0 from 

but then compile this(added flag -g):

#include <stdlib.h>int main () {    int *p = NULL;    p = realloc(p, 0);    return 0;}

valgrind output shows errors(memory leak):

valgrind --leak-check=full --show-leak-kinds=all --track-origins=yes ./test==186749== Memcheck, a memory error detector==186749== Copyright (C) 2002-2017, and GNU GPL'd, by Julian Seward et al.==186749== Using Valgrind-3.15.0 and LibVEX; rerun with -h for copyright info==186749== Command: ./test==186749== ==186749== ==186749== HEAP SUMMARY:==186749==     in use at exit: 0 bytes in 1 blocks==186749==   total heap usage: 1 allocs, 0 frees, 0 bytes allocated==186749== ==186749== 0 bytes in 1 blocks are definitely lost in loss record 1 of 1==186749==    at 0x483B723: malloc (in /usr/lib/x86_64-linux-gnu/valgrind/vgpreload_memcheck-amd64-linux.so)==186749==    by 0x483E017: realloc (in /usr/lib/x86_64-linux-gnu/valgrind/vgpreload_memcheck-amd64-linux.so)==186749==    by 0x10916D: main (test1.c:5)==186749== ==186749== LEAK SUMMARY:==186749==    definitely lost: 0 bytes in 1 blocks==186749==    indirectly lost: 0 bytes in 0 blocks==186749==      possibly lost: 0 bytes in 0 blocks==186749==    still reachable: 0 bytes in 0 blocks==186749==         suppressed: 0 bytes in 0 blocks==186749== ==186749== For lists of detected and suppressed errors, rerun with: -s==186749== ERROR SUMMARY: 1 errors from 1 contexts (suppressed: 0 from 0)

why this is happening even i didnt allocate anything?


Viewing all articles
Browse latest Browse all 22289

Latest Images

Trending Articles



Latest Images

<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>