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
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
Nice .👏
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
Awesome 👏👏
Is it your project or ?
It's a test code i had in my machine. Thought to introduce few error for debugging. Just a sample one.
Oh okay ,all the best
Interesting,it seems like you are working on new things
Thank yaou! Would be happy to connect with you and discuss more about my current project.
Yeah I'm glad for that
How long you have been working on this project
The current one which involved Lidar and Unreal Engine, i have started it a month back.
Oh that's pretty cool
And you have to work much on it
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.
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
Thanks! Will DM you to talk more about this project.
For sure !! Have a coding day ahead 😊