Home > Enterprise >  Stack smashing detected on casting
Stack smashing detected on casting

Time:09-21

I have the following code:

#include <stdio.h>

typedef struct {
  int a, b, c, d, e, f;
}
type1;

typedef struct {
  int a, b, c;
}
type2;

type1 RTE = {
  1,
  2,
  3,
  4,
  5,
  6
};

void copy(type1 * arg) {
  * arg = RTE;
}
int main() {
  // Write C code here
  printf("%d\n", RTE.c);
  type2 local;
  copy((type1 * ) &local);
  printf("%d", local.c);

  return 0;
}

When I run it I get a stack smashing detected error. I suspect it is because of the cast but I can't figure out why. I would be grateful if someone could explain me.

CodePudding user response:

The structure type1 will require double the space in memory required by type2, but you’ve only allocated a variable of type2 in statement type2 local;. This would have been allocated on the stack, since it is a local variable. When the pointer is cast in statement copy((type1 * ) &local);then dereferenced in statement * arg = RTE; inside of function copy, the program will copy the larger contents of RTE into the smaller allocated memory of local basically overflowing. If the stack fills from the bottom up, this would basically corrupt the stack causing failure when the program returns.

As a general practice it is not a good idea to cast between two different types of pointers. Also, for ANSI C the compiler may determine how to arrange struct members relative to the base address for the struct, so it is not safe to assume any particular member of the struct will be transferred any other particular member, regardless of type and definition order.

If you want to copy the contents of an object of type1 into an object of type2, it should be done member by member.

  • Related