mike_b
mike_b

Reputation: 2377

pointer to a variable is not updating variable when dereferenced

This is a debugging problem I've been trying to solve. I know the bit mask I need to apply to make b equal a. I inspected with gdb to find the difference between a and b. The variables b and a are char[] types and set prior to reaching the 'bug'.

#include <string.h>

int main() {
  char a[1] = "a";
  char b[1] = "b";
  int *x;
  x = (int *) b;
  // bug in next line
  *x = *x & 0xffffffff;
  return memcmp(a, b, 1);
}

Until a equals b, I can't solve the problem. The only constraint given is that the bug is in the line noted, no other code is to be changed. There is no rule saying I can't add lines after the bug, though and before the memcmp().The issue I find is that nothing I do to the bit mask changes the value of b, ever. I've set breakpoints and inspected the value of x and *x before and after the bug, but x seems to not change.

Breakpoint 1, main () at test.c:9
9     *x = *x & 0xffffffff;
(gdb) print (int) a
$1 = -6922
(gdb) print (int) b
$2 = -6921
(gdb) print (int) x
$3 = -6921
(gdb) step

Breakpoint 2, main () at test.c:10
10    return memcmp(a, b, 1);
(gdb) print (int) a
$4 = -6922
(gdb) print (int) b
$5 = -6921
(gdb) print (int) x
$6 = -6921

I don't see how this can be solved the way requested, by modifying the constant in the line where the bug is. Any help to understand how to use x to update b using a bitwise mask would be appreciated.

Upvotes: 0

Views: 238

Answers (2)

NathanOliver
NathanOliver

Reputation: 180955

You are trying to change the address of b but in

*x = *x & 0xffffffff;

You are changing the value because you are dereferencing x. Yyou need to apply the manipulation to x itself like

x = x & 0xffffffff;

And then you need to reassign x into b.

This will run afoul of the strict aliasing rules.

Upvotes: 1

Mark Ransom
Mark Ransom

Reputation: 308452

x is a pointer; casting it to an int simply gives you the address as a decimal number.

a and b are both arrays, which will decay to a pointer when you do operations that require a pointer. By casting them to int you're again getting the address of the variable. The address doesn't change with the operation you're performing, even when the contents at that address changes.

Since a and b are both smaller than an int, your code is likely to mess up in ways that are extremely painful. Even if they were the right size, this isn't guaranteed to do the right thing.

Upvotes: 1

Related Questions