Find the bug

#include <stdio.h> #include <stdlib.h> int main() { int *array = malloc(5 * sizeof(int)); int i; for (i = 0; i <= 5; i++) { array[i] = i * 2; } printf("Array values:\n"); for (i = 0; i < 5; i++) { printf("%d\n", array[i]); } int value = 10; int result = value / (5 - i); free(array); return 0; } Expected output: 0 2 4 6 8
15 Replies
nour_oud
nour_oud7mo ago
hmm 🤔, the errors lie here: 1. int *array = malloc(5 * sizeof(int)); 2. The loop condition in for loop it should be i < 5 instead of i <= 5. 3. The division by (5 - i) can lead to a division by zero
Yash Naidu
Yash Naidu7mo ago
Nice .👏
Saßì
Saßì7mo ago
The bug in your code is in the loop condition. The loop should iterate from 0 to 4 (inclusive), but you have used 'i'<= 5, which results in accessing the array out of bounds. Also, you are using the variable i outside its valid scope in the division calculation. Here's the corrected code: #include <stdio.h> #include <stdlib.h> int main() { int *array = malloc(5 * sizeof(int)); int i; for (i = 0; i < 5; i++) { array[i] = i * 2; } printf("Array values:\n"); for (i = 0; i < 5; i++) { printf("%d\n", array[i]); } int value = 10; int result = value / (5 - i); // Note: i is out of scope here. free(array); return 0; } Now, the loop conditions are corrected, and the use of i is within its valid scope. @Yash Naidu hope it helps you
Yash Naidu
Yash Naidu7mo ago
Awesome 👏👏
Saßì
Saßì7mo ago
Is it your project or ?
Yash Naidu
Yash Naidu7mo ago
It's a test code i had in my machine. Thought to introduce few error for debugging. Just a sample one.
Saßì
Saßì7mo ago
Oh okay ,all the best Interesting,it seems like you are working on new things
Yash Naidu
Yash Naidu7mo ago
Thank yaou! Would be happy to connect with you and discuss more about my current project.
Saßì
Saßì7mo ago
Yeah I'm glad for that How long you have been working on this project
Yash Naidu
Yash Naidu7mo ago
The current one which involved Lidar and Unreal Engine, i have started it a month back.
Saßì
Saßì7mo ago
Oh that's pretty cool And you have to work much on it
Yash Naidu
Yash Naidu7mo ago
Indeed. I am pretty new to that stuff. Trying to get my way around it. Still in the learning phase, literature review. Yet to implement it practically.
Saßì
Saßì7mo ago
What inspired you to work on it, and how has the progress been in the past month? I appreciate your new beginning, hope you are gonna yield much outcome from it
Yash Naidu
Yash Naidu7mo ago
Thanks! Will DM you to talk more about this project.
Saßì
Saßì7mo ago
For sure !! Have a coding day ahead 😊