TGViewer
C++ - Reddit C++ - Reddit @r_cpp · 229 subscribers
Post #24127 14
Why does this code behave like this?

```cpp

#include <cstdlib>
#include <cstdio>
int main()
{
int *a = (int *)malloc(sizeof(int));
*a = 42;

for (int i = 1; i < 10; i++) {
a[i] = i;
}
for (int i = 0; i < 10; i++) {
printf("%d\n", a[i]);
}
}
Ouput :
malloc(): corrupted top size
Aborted (core dumped)
```
this is understandable that we are getting error over here but when we add a printf() after *a = 42. we do not get this error why is that
```cpp

#include <cstdlib>
#include <cstdio>
int main()
{
int *a = (int *)malloc(sizeof(int));
*a = 42;
printf("%d\n", a[0]);

for (int i = 1; i < 10; i++) {
a[i] = i;
}
for (int i = 0; i < 10; i++) {
printf("%d\n", a[i]);
}
}
Ouput :
42
42
1
2
3
4
5
6
7
657975
668983
```
can anyone explain reasoning behind this behaviour

https://redd.it/1oi40qg
@r_cpp
Reddit From the cpp community on Reddit Explore this post and more from the cpp community
More from @r_cpp
  1. Oct 14, 2026I tested whether a coding agent would use C++23 ranges without being told Blog post: https…
  2. Oct 14, 2026C++ futures part 1: The mental model https://devblogs.microsoft.com/oldnewthing/20261012-0…
  3. Oct 14, 2026C++ futures part 2: The mental model for std::promise, std::packaged_task https://devblogs…
  4. Oct 12, 2026[Release] slick-logger v2.2.0 — Lock-free asynchronous C++20 logging with multi-process sh…
  5. Oct 12, 2026Cheap alternative to reboot parameters (nohz, rcu, isolcpus) for stable benchmarks When no…
  6. Oct 12, 2026This C++ drama is crazy - Adobe votes no https://www.youtube.com/watch?v=DEqx_NMMH9Q https…
Threads Profile ViewerView any public Threads profile without an account.Open ThreadLook →Writing with AI? Make it sound human.Metric37 rewrites AI drafts so they read naturally. Free AI detector, 1,500 words free.Try Metric37 →