bd satish wrote:
Hello,
I wrote my own version of memchr( ) but looks like it is clashing
with GCC's builtin function of same name. I'm not able to set any
breakpoint.
How should I over-ride this ?
Here is the code I wrote:
----- memchr.cpp ----
void* memchr(const void* str, int ch, size_t count)
{
unsigned char* buf = (unsigned char*)str;
unsigned char c = ((unsigned char)(ch));
register unsigned int i;
for(i=0; i<count; i++)
{
if(*buf == c) return (void*)buf;
buf++;
}
return NULL;
}
I compiled the above like:
g++ -c -g -Wall -ansi -nostdinc -nostdinc++ -fno-builtin
fno-nonansi-builtins -Wshadow memchr.cpp
And to test the above code, here is a simple main( )
--- test_memchr.cpp ---
int main( )
{
const char msg[ ] = "Hello World";
char x; char *c=&x;
c = (char*)memchr(msg, 'X', 10);
return *c;
}
The above was compiled as
g++ -g -Wall -nostdinc++ -nostdinc -fno-builtin test_memchr.cpp memchr.o
The program gives a segmentation fault ! And I can't put a breakpoint
even though "-g" is specified.
My guess is that I'm somewhere calling GCC's in built memchr instead
of mine. Can somebody help me where am I going wrong ?
-- Satish.BD
I just done this on my laptop seems to work fine:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
void* memchr( const void* str, int ch, size_t count )
{
unsigned char c= (unsigned char)ch;
const char* dt= (const char*) str;
unsigned int i= 0;
for( ; i< count; ++i )
{
if( dt[i] == c )
return (void*)dt;
}
return NULL;
}
int main( )
{
const char *msg= "Hello World";
char *pch = (char*)memchr(msg, 'W', strlen(msg));
if (pch!=NULL)
printf ("'X' found at position %li.\n", pch-msg+1 );
else
printf ("'X' not found.\n");
return 0;
}
just based it off your code, just compiled with gcc test.c, its not that
clean or safe in my opinion, too many casts i think.