w3resource

C memchr() function

C memchr() function - find byte in memory

The memchr() function is used to search the first n bytes of buf for the first occurrence of c converted to an unsigned character.

Use memchr() function when:

  • Raw memory searches: Unlike strchr(), which is limited to null-terminated strings, memchr() works on memory blocks that may not end with a null terminator.
  • Custom memory sizes: memchr() lets us specify an exact number of bytes to search within, making it handy for processing portions of larger data blocks.
  • Performance needs: In cases where scanning for a single occurrence is faster than iterating over the entire block, memchr() provides a more efficient alternative to writing a loop for the search.

Syntax:

void *memchr(const void *buf, int c, size_t n)

Parameters:

Name Description Required /Optional
buf Pointer to buffer. Required
c Character to look for. Required
n Number of characters to check. Required

Return value from memchr()

The memchr() function returns a pointer to the location of c in buf. It returns NULL if c is not within the first count bytes of buf.

Examples: memchr() function

Example 1: Locate a specific character in a string.

The following memchr() example demonstrates how to locate a specific character in a string. It checks for two different characters in a given text and identifies their positions. By using memchr(), the program searches for each character within a specified length of the string. If a character is found, its position is printed; if not, a message indicates it was not found in the text. This is useful for quickly locating characters in a block of memory without iterating manually through each byte.

Code:

#include <stdio.h>
#include <string.h>

int  ch1= 'A', ch2 = 'a';
char text[] = "C programming language.";
int main()
{
   char *pdest;
   int result;
   printf("Original String: %s", text );
   printf("\n\nCheck the character %c present in the said text!",ch1);
   pdest = (char *)memchr(text, ch1, strlen(text));
   result = (int)(pdest - text + 1);
   if ( pdest != NULL )
      printf( "\n%c found at position %d\n", ch1, result );
   else
      printf("\n%c not found!",ch1 );
   printf("\n\nCheck the character %c present in the said text!",ch2);
   pdest = (char *)memchr(text, ch2, strlen(text));
   result = (int)(pdest - text + 1);
   if ( pdest != NULL )
      printf( "\n%c found at position %d\n", ch2, result );
   else
      printf("\n%c not found!",ch2);
 return 0;
}

Output:

Original String: C programming language.

Check the character A present in the said text!
A not found!

Check the character a present in the said text!
a found at position 8

Example 2: Find a Character in a custom length of memory

In this example, we'll search for a specific character within the first 10 bytes of a sentence.

Code:

#include <stdio.h>
#include <string.h>
int main() {
    // Define a string to search within
    char text[] = "Hello, C programming!";
    // Character to search for
    char target = 'C';
    // Maximum number of bytes to search
    size_t length = 10;

    // Use memchr to find the character within the specified length
    char *result = (char *)memchr(text, target, length);

    // Check if the character was found within the specified range
    if (result != NULL)
        printf("Character '%c' found at position %ld within first %zu bytes.\n", target, (result - text + 1), length);
    else
        printf("Character '%c' not found within the first %zu bytes.\n", target, length);

    return 0;
}

Output:

Character 'C' found at position 8 within first 10 bytes.

Explanation:

  • We limit the search to the first 10 bytes of the string to see if memchr() can locate the letter 'C' within that range.
  • If 'C' is found, we print its position; otherwise, we print that it was not found within the range.

Example 3: Search for a character in binary data

In this example, we have demonstrated how memchr() function can be used to search through raw binary data, such as an array of integers, to locate a specific byte.

Code:

#include <stdio.h>
#include <string.h>

int main() {
    // Define an array of integers (binary data)
    int data[] = {0x12345678, 0x9abcdef0, 0x13579bdf, 0x2468ace0};
    // Target byte (last byte of 0x9abcdef0)
    char target_byte = 0xf0;

    // Calculate the size in bytes of the data array
    size_t data_size = sizeof(data);

    // Use memchr to search for the target byte within the binary data
    char *result = (char *)memchr(data, target_byte, data_size);

    // Check if the byte was found within the binary data
    if (result != NULL)
        printf("Byte 0x%x found at byte offset %ld.\n", target_byte, result - (char *)data);
    else
        printf("Byte 0x%x not found in the binary data.\n", target_byte);

    return 0;
}

Output:

Byte 0xfffffff0 found at byte offset 4.

Explanation:

  • Library Inclusion: Includes <stdio.h> and <string.h> libraries for input/output functions and memory operations.
  • Main Function: Starts the main function, where the program execution begins.
  • Integer Array Definition: Defines an integer array data containing four 32-bit hexadecimal values, which represent binary data.
  • Target Byte Definition: Defines target_byte as 0xf0, which is the byte value to search for in the data array. This corresponds to the last byte of the second element in data (0x9abcdef0).
  • Data Size Calculation: Calculates the total byte size of the data array using sizeof(data) and stores it in data_size.
  • Byte Search with memchr: Uses memchr() to search for target_byte within data. memchr() returns a pointer to the first occurrence of target_byte if found, or NULL if not found.
  • Pointer Typecast: Typecasts data to (char *) because memchr() operates on byte-level data rather than integer arrays.
  • Conditional Check: Checks if result is not NULL, indicating that target_byte was found in data.
    • If found, it prints the hexadecimal value of target_byte and its offset in bytes from the beginning of data.
    • If not found, it outputs that target_byte is not present in data.
  • Program End: The main function returns 0, indicating successful completion of the program.

C Programming Code Editor:



Previous C Programming: C string.h Home
Next C Programming: C memcmp()



Follow us on Facebook and Twitter for latest update.