Why does printf sometimes fix bugs?
1st of all, use the code tags in the editor ('<>' symbol) to be easier to read the code.
2nd, I have run into that issue a few times myself and the answer usually lies in the fact that there are some funny businesses in the code (unless you are using multiple threads, in which case it could be some problem with memory consistency since printfs and other IO operations usually impose memory barriers (and cache coherence) if I am not mistaken).
In your case, however, it would probably do you good to correct the mistakes that you have made and see if the "printf effect" resolves by itself (gcc in linux spits out compilation warnings and even with the printf the program just crashes in runtime).
The main problem lies in the line
int *screen = (int*)malloc((height)*(base));
which affects pretty much everything that follows.
You are allocating an array of size height*base but you forgot to multiply this by the sizeof(int). Right now it is allocating height*base bytes instead of height*base integers.
Obviously, since you are assuming that every position is an int, pointer arithmetic will soon break.
Also, when you free screen at the end of main, you forgot that screen is no longer a pointer to the start of the array, so you are trying to deallocate memory that was not allocated in the first place. You should always keep a pointer to the beginning of any allocated memory.
Create an account or sign in to comment
You need to be a member in order to leave a comment
Create an account
Sign up for a new account in our community. It's easy!
Register a new accountSign in
Already have an account? Sign in here.
Sign In Now