i am unable to use malloc and free using stdio.h library - c

I have the following issue/question:
I'm currently working on visual studio in C
I made a program that uses the functions malloc and free, I am sure I used them well, but when I try to compile I get the following errors:
Error C3861 'free': identifier not found
Error (active) identifier "free" is undefined
(same errors for malloc)
the only include statement I made was for stdio.h (which I usually add and it works fine for these functions)
I added stdlib and the problem was resolved, but when I serve this chore I may be downgraded for including a library we did not work with so far, can anyone tell me why the functions don't work with just stdio.h?

<stdlib.h> is the correct header to include when calling malloc and free. In fact, it's correct to say that you must include <stdlib.h> (directly or indirectly) when calling malloc and free.
There are lots of reasons why it might have worked for you once before even though you didn't. Without seeing that older code, I couldn't say why. Don't worry about it. Just always include <stdlib.h> when calling malloc and free.

Malloc and free is defined under stdlib.h. So without including it your program wont work.

Related

Providing a `malloc` implementation for `newlib-nano`

I'd like to provide an implementation of malloc for newlib-nano when using it with gcc. In my situation, I have some source file, say main.c, that calls strftime. The newlib-nano implementation of strftime uses malloc. In a header file, my_memory.h, I've declared a function void *malloc(size_t size) and provided an implementation in a corresponding my_memory.c file.
When linking the project using gcc, the linker fails at .../libc_nano.a(liba-malloc.o) because of multiple definitions of malloc. The behavior I'd like is for the linker to take my implementation of malloc rather than pulling newlib-nano's, but to retain using newlib-nano's implementation of other standard library functions, e.g. memset.
I've searched around for an "exclude object file from static library" option in gcc to try to exclude libc_nano.a(liba-malloc.o) but with no luck. Note that the compiler is pulling in this object file and I don't have access to the compiler's libc_nano.a to patch liba-malloc.o with my own object file.
Anyway, am I missing something, or is it not possible to achieve what I'm trying to achieve?
Likely liba-malloc.o contains other allocator function definitions like calloc, free, realloc, etc. and thus is getting pulled in for linking because of references to one of them. You can see this with the -t option to ld (pass -Wl,-t on gcc command line when linking to use it). If this is the case, you can avoid linking it just by ensuring you've provided definitions of all these functions yourself.
A better idea might be getting rid of the malloc dependency by using a different strftime. It's rather ridiculous for strftime, especially an embedded-oriented implementation, to be calling malloc; it has no fundamental need to and I'm somewhat baffled how they found a way to make malloc useful to it. Aside from some tie-in with locale which could be extricated fairly easily, musl libc's strftime.c (disclosure: author=me) is very self-contained and could probably serve as a drop-in replacement.

Should Mac OSX have a "malloc.h" file? [duplicate]

This question already has answers here:
difference between <stdlib.h> and <malloc.h>
(6 answers)
Closed 3 years ago.
A customer's code is expecting to find an include file malloc.h in one of the "usual suspect" locations. On my Mac, AFAICT, there is no malloc.h, at least not in any place you would expect to find it, such as /usr/include, /usr/local/include, or /opt/local/include. Since the malloc() is usually defined in stdlib.h, and since the code includes stdlib.h anyway, I was able to get the code to build by just commenting out the few includes of malloc.h. I am building with gcc.
But two questions: Is my gcc messed up somehow? Should that file be there? Also, the code bombs almost immediately with a seg fault that I haven't been able to track down yet. Could this be the consequence of using the wrong malloc()?
The malloc.h is deprecated and should not be used. It contains some non-standard functions too. If you want to use malloc, then include stdlib.h. Not even the C89 standard mentions malloc.h
If it's the cause of your problems, I don't know, but it's quite probable.
The listing below can provide ideas on where the file should/could be found. I can't explain the segfault without more details, though. I do not see how it could be related to malloc() in any way.
/Library/Developer/CommandLineTools/SDKs/MacOSX.sdk/usr/include/sys/malloc.h
/Library/Developer/CommandLineTools/SDKs/MacOSX.sdk/usr/include/malloc/malloc.h
/Library/Developer/CommandLineTools/SDKs/MacOSX.sdk/System/Library/Frameworks/Kernel.framework/Versions/A/Headers/sys/malloc.h
/Applications/Xcode.app/Contents/Developer/Platforms/AppleTVOS.platform/Developer/SDKs/AppleTVOS.sdk/usr/include/malloc/malloc.h
/Applications/Xcode.app/Contents/Developer/Platforms/iPhoneOS.platform/Developer/SDKs/iPhoneOS.sdk/usr/include/malloc/malloc.h
/Applications/Xcode.app/Contents/Developer/Platforms/WatchOS.platform/Developer/SDKs/WatchOS.sdk/usr/include/malloc/malloc.h
/Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX.sdk/usr/include/sys/malloc.h
/Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX.sdk/usr/include/malloc/malloc.h
/Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX.sdk/System/Library/Frameworks/Kernel.framework/Versions/A/Headers/sys/malloc.h
/Applications/Xcode.app/Contents/Developer/Platforms/WatchSimulator.platform/Developer/SDKs/WatchSimulator.sdk/usr/include/malloc/malloc.h
/Applications/Xcode.app/Contents/Developer/Platforms/AppleTVSimulator.platform/Developer/SDKs/AppleTVSimulator.sdk/usr/include/malloc/malloc.h
/Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator.sdk/usr/include/malloc/malloc.h
$

Overloading free() so my program use mine instead of the system's

I need to recode the free() func for educational purpose and it must be named free() also.
When i rename my function myfree() it work flawlessly but when i name it free() the program don't know if he need to use mine or the system's so the program just Segmentation fault(core dumped) even if i don't call my free (just the declaration of another free() func seem to crash it)
so how can i tell the compiler to use mine instead of the system's ?
thanks you in advance.
EDIT : Linux operating system
Basically, you have three options that I can see
Redirect it during compile time, for example using #define as #Mohamed suggests.
Change it at runtime using LD_PRELOAD.
Modify the existing malloc/free using malloc hooks.
If you're using GCC, you can use the compiler to help you. When you compile, include this on your link line: -Xlinker --wrap=free. This will redirect all calls to free() to use __wrap_free(), which you must provide. If you wish to call the original free() function, it's still there but renamed; you can call __real_free().
This will capture pre-compiled libraries you link against, something a macro cannot do (but LD_PRELOAD can).
use macros for that: to force program to use your myfree() function:
#define free(X) myfree(X)
The easiest (not the safest) way is to #define free myfree so the preprocessor will replace all calls from free() to myfree(). Another, more safe approach, would be create a normal function called free() and do not include libraries, that also contain free() function.
If you are looking for a standard way, I'm afraid it doesn't exist. Redefining standard library names is undefined behavior.
C11, 7.1.3.2:
... If the program declares or defines an identifier in a
context in which it is reserved (other than as allowed by 7.1.4), or defines a reserved
identifier as a macro name, the behavior is undefined.
In 7.1.4, there are is a long explanation of how the library may define a macro with the same name as the function and how to bypass that macro. There is no indication of how a user may override a standard library function.
You can also see this question for more information.
Non standard ways are of course always possible as you can find in other answers.

dlmalloc crash on Win7

For some time now I've been happily using dlmalloc for a cross-platform project (Windows, Mac OS X, Ubuntu). Recently, however, it seems that using dlmalloc leads to a crash-on-exit on Windows 7.
To make sure that it wasn't something goofy in my project, I created a super-minimal test program-- it doesn't do anything but return from main. One version ("malloctest") links to dlmalloc and the other ("regulartest") doesn't. On WinXP, both run fine. On Windows 7, malloctest crashes. You can see screencasts of the tests here.
My question is: why is this happening? Is it a bug in dlmalloc? Or has the loader in Windows 7 changed? Is there a workaround?
fyi, here is the test code (test.cpp):
#include <stdio.h>
int main() {
return 0;
}
and here is the nmake makefile:
all: regulartest.exe malloctest.exe
malloctest.exe: malloc.obj test.obj
link /out:$# $**
regulartest.exe: test.obj
link /out:$# $**
clean:
del *.exe *.obj
For brevity, I won't include the dlmalloc source in this post, but you can get it (v2.8.4) here.
Edit: See these other relavent SO posts:
Is there a way to redefine malloc at link time on Windows?
Globally override malloc in visual c++
Looks like a bug in the C runtime. Using Visual Studio 2008 on Windows 7, I reproduced the same problem. After some quick debugging by putting breakpoints in dlmalloc and dlfree, I saw that dlfree was getting called with an address that it never returned earlier from dlmalloc, and then it was hitting an access violation shortly thereafter.
Thankfully, the C runtime's source code is distributed along with VS, so I could see that this call to free was coming from the __endstdio function in _file.c. The corresponding allocation was in __initstdio, and it was calling _calloc_crt to allocate its memory. _calloc_crt calls _calloc_impl, which calls HeapAlloc to get memory. _malloc_crt (used elsewhere in the C runtime, such as to allocate memory for the environment and for argv), on the other hand, calls straight to malloc, and _free_crt calls straight to free.
So, for the memory that gets allocated with _malloc_crt and freed with _free_crt, everything is fine and dandy. But for the memory that gets allocated with _calloc_crt and freed with _free_crt, bad things happen.
I don't know if replacing malloc like this is supported -- if it is, then this is a bug with the CRT. If not, I'd suggest looking into a different C runtime (e.g. MinGW or Cygwin GCC).
Using dlmalloc in cross-platform code is an oxymoron. Replacing any standard C functions (especially malloc and family) results in undefined behavior. The closest thing to a portable way to replace malloc is using search-and-replace (not #define; that's also UB) on the source files to call (for example) my_malloc instead of malloc. Note that internal C library functions will still use their standard malloc, so if the two conflict, things will still blow up. Basically, trying to replace malloc is just really misguided. If your system really has a broken malloc implementation (too slow, too much fragmentation, etc.) then you need to do your replacement in an implementation-specific way, and disable the replacement on all systems except ones where you've carefully checked that your implementation-specific replacement works correctly.

Is there a way to redefine malloc at link time on Windows?

I would like to replace the default malloc at link time to use a custom malloc. But when I try to redefine malloc in my program, I get this error:
MSVCRT.lib(MSVCR80.dll) : error LNK2005: _malloc already defined in test.lib(test.obj)
This works perfectly on any Unix, and it works on Windows with most functions, but not with malloc. How can I do this? And what is different with malloc that disallow overriding it?
I know I could replace every call to malloc with my custom malloc, or use a macro to do this, but I would rather not modify every third party library.
There is really good discussion of how hard this is here:
http://benjamin.smedbergs.us/blog/2008-01-10/patching-the-windows-crt/
Apparently, you need to patch the CRT
Edit: actually, a MS employee gave the technique in the discussion. You need to move your malloc to a lib, and then link it before the CRT
"he also mentions that if you link your malloc as a lib before the CRT (i.e. make sure to turn on ‘ignore default libs’ and explictly include the CRT), you’ll get what you want, and can redistribute this lib without problems."
I think it depends in which order you link the files. I think you need to link your custom function first, then the import library.
From version 3.0 Firefox uses a custom allocator (AFAIR jmalloc) -- you could check how they did it. I read that they had some problems with it. You may check this blog post.
What about defining malloc=_custom_malloc in the project makefile.
Than adding a file such as:
my_memory.c
#undef malloc
#undef calloc
...
void *_custom_malloc(int size) { return jmalloc(size); }
void *_custom_calloc(int size) { return jcalloc(size); }
...

Resources