-4

Assume I have the following:

wchar_t *x = L"myname";
void *y = 0; // assume that p is already assigned previously to any given buffer

How can I determine if the unicode char pointer x is inside the void* y buffer?

Basically

How can I find a needle in a haystack provided that the haystack is a void pointer, and the needle is a unicode char pointer?

tckmn
  • 57,719
  • 27
  • 114
  • 156
Farrell32
  • 7
  • 3
  • It is not since `y` is null and therefore points nowhere. I don't think you're asking what you really mean to ask. As you trying to figure out if a pointer points into the memory space occupied by a string? – Carey Gregory Nov 14 '15 at 01:48
  • I said assume that y is already filled, i just defined it so that no troll -1s and then asks "how come you didnt even define y"? – Farrell32 Nov 14 '15 at 01:50
  • We still dont know what you are trying to do – pm100 Nov 14 '15 at 01:52
  • are you trying to find out if the pointer y points to a location in x, or are you trying to see if y points to some character and that character also exists in x. Or are you trying to discover if the buffer pointed at by Y has the string x in it somewhere – pm100 Nov 14 '15 at 01:53
  • Don't tell us to assume things about your code while showing something completely different. It just muddles your question. Maybe show something like this: `void *y = RandomMemoryLocation();` and explain that it's an imaginary function that returns a valid but random pointer value. – Carey Gregory Nov 14 '15 at 01:54
  • 1
    And people who downvote your question for being unclear aren't called trolls. They're called users who know a poor question when they see it. – Carey Gregory Nov 14 '15 at 01:55

1 Answers1

1

If you know the length of the buffer in bytes, you could just do this.

#include <stdbool.h>
char *tmp = x; //you can do byte arithmetic on char*, but not on void*
bool is_in_buffer = ((char*)y >= tmp && (char*)y < tmp + length);

since you know the length of the buffer and the buffer is stored in contiguous memory, if y is within the bounds of the buffer, you know y is in the buffer.

note that you can only assign pointers of non char type to char and void. Doing otherwise violates the strict aliasing rule, which is present in C99 and C11.

Bobby Sacamano
  • 540
  • 4
  • 15
  • Thank-you bobby for providing a proper answer without causing any uncalled-for trouble like 95% of the people on stack. +1 – Farrell32 Nov 14 '15 at 01:56
  • I know it can be a bit painful, but they cause trouble for a reason. I had to make a couple assumptions when answering your question. – Bobby Sacamano Nov 14 '15 at 01:59
  • @Farrell32 Oddly, the vast majority of other users here don't seem to have the problem you do. I wonder why that is. – Carey Gregory Nov 14 '15 at 02:00