Skip to content

Instantly share code, notes, and snippets.

@vivithemage
Last active August 26, 2024 02:25
Show Gist options
  • Save vivithemage/9489378 to your computer and use it in GitHub Desktop.
Save vivithemage/9489378 to your computer and use it in GitHub Desktop.
libmagic.h example
#include <stdio.h>
#include <magic.h>
int main(void)
{
char *actual_file = "/file/you/want.yay";
const char *magic_full;
magic_t magic_cookie;
/* MAGIC_MIME tells magic to return a mime of the file,
but you can specify different things */
magic_cookie = magic_open(MAGIC_MIME);
if (magic_cookie == NULL) {
printf("unable to initialize magic library\n");
return 1;
}
printf("Loading default magic database\n");
if (magic_load(magic_cookie, NULL) != 0) {
printf("cannot load magic database - %s\n", magic_error(magic_cookie));
magic_close(magic_cookie);
return 1;
}
magic_full = magic_file(magic_cookie, actual_file);
printf("%s\n", magic_full);
magic_close(magic_cookie);
return 0;
}
@realnc
Copy link

realnc commented Feb 8, 2016

Warning: magic_load(magic_cookie, NULL) wont pass memory debugger like electricfence.

You have to provide a filename or libmagic tries a malloc(0) which may provide unpredictable result later. magic_load(session->magic,"/usr/share/misc/magic.mgc") pass.

malloc(0) is perfectly fine and allowed. Passing NULL to magic_load() is the recommended way of doing this. Do not pass a filename if you want your code to use the default file and be portable.

@amr3k
Copy link

amr3k commented Jan 21, 2019

Hello, thanks for this example, when I run it it gives this output:
collect2: error: ld returned 1 exit status

@amr3k
Copy link

amr3k commented Jan 24, 2019

Hello, thanks for this example, when I run it it gives this output:
collect2: error: ld returned 1 exit status

Fixed with gcc -g test.c -lmagic

@jetX11
Copy link

jetX11 commented Oct 25, 2021

Hello. It's a very clear and useful example. Thanks.
Isn't it necessary to free the memory allocated by magic_file function (memory pointed by magic_full in this example)? Would magic_close take care of that (and all the subsequent calls of magic_file)?


apparently, it is not necessary. I got this runtime error:
free(): double free detected in tcache 2

@vassilit
Copy link

Hello. It's a very clear and useful example. Thanks. Isn't it necessary to free the memory allocated by magic_file function (memory pointed by magic_full in this example)?

No, libmagic is managing its own storage and magic_file returns a pointer into that storage. magic_close() probably frees the heap.
The manpage gives the declaration const char *magic_file(magic_t cookie, const char *filename);, the const qualifier seems to mean that they retains «ownership» over the data and so the storage.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment