I am searching for "bad/broken" c code that I can use test a error handler on a mcu based system.
I am searching for code that will break during runtime.
So go crazy, what small pieces of code do you have in your back pocket that could be used to break a system. And should be handled by a error handler to avoid uncontrolled behaviour.
/Thanks
I will begin with a couple of examples.
Write to a null pointer
int* pointer = 0x0;
*pointer =开发者_运维问答 0xBAADC0DE;
Write a value to a pointer that is unvalid
int* pointer = 0xCAFEBABE;
*pointer = 0xDEADBEEF;
Jump to a unvalid function pointer
int (*fpBabe)() = 0xDEADBABE;
fpBabe();
So do you have some more bad things that you could throw at a error handler?
Divide by zero (and simple math to get at it in case the compiler tries to optimize it away):
int i = argc;
return 34/(argc-i);
Try accessing a high mem address, as well as a low one:
char *v = ~0;
*v = '\0';
If you have a heap mgmt library, try freeing twice:
char *ptr = malloc(4096);
free(ptr); free(ptr);
Try allocating memory without abandon:
for(;;)
malloc(4096);
Try to exhaust the stack:
int foo(int arg) { return foo(arg+1); }
int main(int a, char *v[]) { return foo(1); }
int f() { return f() + f(); }
int g() { return g(); }
int h() { while(1); }
Exhaust the stack by mutual recursion (might be harder to detect):
int f(void) { return g(); }
int g(void) { return f(); }
int main(void) { return f(); }
...or by funny signal handling:
void handler(int n) { raise(n); raise(n); }
int main(void) { signal(SIGINT, &handler); raise(SIGINT); return 0; }
Destroy the heap:
for (char *x = malloc(1); *x++ = 42;);
Destroy the heap and blame free():
char *x = malloc(1);
for (int i = 0; i < 100; x[i++] = 42);
free(x); // free() will probably segfault
Write past the end of a buffer:
char dest[5];
const char* src = "a bigger source";
strcpy(dest,src);
or
dest[5]='\0';
精彩评论