-1

When I use the function I only receive NULL, is there anything wrong that I do? I am trying to read a file in a binary way and then to find out if there is a specific signature there

Here is my code:

#include <stdio.h>
void *memmem(const void *haystack, size_t haystack_len, const void * const needle, const size_t needle_len);
#define TEXT2 "hey"

int main(void)
{   
    unsigned char* buffer = NULL;
    FILE* file = fopen("lol.txt", "rb");

    long bufferLen = 0;

    fseek(file, 0, SEEK_END);
    bufferLen = ftell(file);
    fseek(file, 0, SEEK_SET);

    buffer = (char*)calloc(bufferLen, sizeof(char));


    fread(buffer, sizeof(char), bufferLen, file);
    fclose(file);

    char *pos = memmem(buffer, bufferLen, TEXT2, sizeof(TEXT2));

    if (pos != NULL)
        printf("hey");

    getchar();
    return 0;
}


void *memmem(const void *haystack, size_t haystack_len, const void * const needle, const size_t needle_len)
{
    if (haystack == NULL) return NULL; // or assert(haystack != NULL);
    if (haystack_len == 0) return NULL;
    if (needle == NULL) return NULL; // or assert(needle != NULL);
    if (needle_len == 0) return NULL;

    for (const char *h = haystack; haystack_len >= needle_len; ++h, --haystack_len) 
    {
        if (!memcmp(h, needle, needle_len)) 
        {
            return h;
        }
    }
    return NULL;
}

I tried to do it, but it always returning me null is there any ideas? am I doing anything wrong?

id0 SI
  • 15
  • 3

1 Answers1

2
char *pos = memmem(buffer, bufferLen, TEXT2, sizeof(TEXT2));
//                                           ^^^^^^^^^^^^^

sizeof "hey" is 4. "hey" has type char[4].

Replace with strlen("hey")

char *pos = memmem(buffer, bufferLen, TEXT2, strlen(TEXT2));
pmg
  • 106,608
  • 13
  • 126
  • 198