thus preventing someone from stealing my code or idea.
You're on a public Q&A site asking for ideas and code from others, who you want to share willingly with you, so sharing your ideas of which the answers help others is how we all learn, and is fair.
If you're learning, it's likely it's not anything new, or certainly not something not already on a million blogs/tutorials or all over Stack already.
If you have specific code, you can make it generic before posting it, as long as it remains relevant to the issue and still describes your issue accurately.
This world and most things in it have advanced due to the sharing of ideas, in science, humanity, business, government, etc.
If you expect others to share with you, surely it's only fair to share with others? The answers you receive are for others to use, as I'm sure you have (or certainly will) use other questions and answers already here on Stack, and other sites.
It so happens that when I submit the code for grading in my university my instructor or some software might search for same code on net to make sure it's not plagiarized.
Simply don't ask for your work to be done for you, instead ask in the way Stack is designed, that is help with parts of your code, bits you are stuck with, specific scenarios or functions etc.
The fact you are showing knowledge in your code and workings and are asking for help is not going to go against you.
Any uni instructor who is against this is stupid. You cannot magically know everything about the course you are doing, so learning, asking, reading, researching is all part of it.
The issue would be if you said "write me code that does XYZ" and then you submitted it as your own.
Even after the fact that it's my own code, I may be held accountable for cheating/copying it from internet.
See above. Just don't copy full code, ask for help on the code you are writing, which is what Stack is about anyway, you shouldn't ask for full code, and many of the better experts and professionals wont give you it, so better ask for help in something specific than your work done for you.
This way you learn better anyway as you understand what answers people are giving you.
I have this code XYZ, it doesn't do ABC, why
The answer will be pointing out a flaw in your code, and not doing your work for you.
If you're still worried, ask your instructor what is acceptable :)