-1
#include <stdio.h>

int main(void) {
    int *x, *y;
    x = malloc(sizeof(int));
    for (int i = 0; i < 4; i++)
        x[i] = i + 1;
    y = x;
    for (int i = 0; i < 4; i++)
        printf("%d ", y[i]);
}

This works correct and outputs 1 2 3 4. But when i < 1000000 it gives segmentation fault. Can someone explain this?

chqrlie
  • 131,814
  • 10
  • 121
  • 189
  • You need to allocate a large enough buffer. You only allocate sizeof(int) which is 4 bytes typically. Can't store 1000000 elements in that! – th33lf Sep 02 '20 at 08:37
  • 2
    It **appears** to work correct, because it's undefined behavior. Your compiler could have chosen to format your hard drive instead, but it didn't. Better try not to trigger undefined behavior in your programs. – cmaster - reinstate monica Sep 02 '20 at 08:39
  • then this means if i don't have any enough buffer for i<4 it also give seg fult – Fatih Solak Sep 02 '20 at 08:39
  • 2
    You have enough memory for `i==0`; Everything else only "works" out of pure luck. – Gerhardh Sep 02 '20 at 08:48
  • @FatihSolak Segfault is the OS warning you that you are accessing memory that is not assigned to your process. Remember - C *does not* warn you for out-of-bounds memory access. It is your responsibility as the programmer to ensure you don't. You could be programming in an environment with no OS and you would have crashed your plane or sunk your ship before you figured out something is wrong! – th33lf Sep 02 '20 at 08:50
  • 1
    @Gerhardh I'd say, bad luck. – Sourav Ghosh Sep 02 '20 at 09:09
  • [What is undefined behavior and how does it work?](https://software.codidact.com/questions/277486). – Lundin Sep 02 '20 at 09:43
  • @Lundin That seems interesting. Did you thought about to maybe import your Q&A to here (even if its got duped by [the one and only](https://stackoverflow.com/q/2397984/12139179) or are there any terms which prohibit this? – RobertS supports Monica Cellio Sep 02 '20 at 10:01
  • @RobertSsupportsMonicaCellio The plan is rather to move everything to Codidact over time. The software community there has not yet decided if/what we will import, or even the scope of the site, it has only been up a few weeks. License-wise there should be no problem importing/exporting between the two sites, AFAIK. – Lundin Sep 02 '20 at 10:34

4 Answers4

3

You need to allocate a large enough buffer. You only allocate sizeof(int) which is 4 bytes typically and large enough to hold only one integer. Can't store 1000000 elements in that. It worked for 4 elements out of pure chance, probably because although you were overwriting memory, you didn't clobber anything important. Something like this is what you should use.

#include <stdio.h>

int main(void)
{
    int count = 1000000;
    int *x, *y;
    x = malloc(sizeof(int) * count);
    for (int i=0; i < count; i++)
        x[i] = i+1;
    y = x;
    for (int i=0; i < count; i++)
        printf("%d ", y[i]);
    
}
th33lf
  • 2,177
  • 11
  • 15
1

Undefined behaviour is undefined, you cannot justify any outcome whatsoever.

You have memory allocated for one integer, the moment you try to dereference the memory outside that range (i.e., i == 1), you're invoking UB. The only valid access is x[0] and x[0] only.

Sourav Ghosh
  • 133,132
  • 16
  • 183
  • 261
1

You only allocated memory for one int:

x = malloc(sizeof(int));   // malloc allocates a memory chunk to only hold one int object.

Indexing x at x[i] = i+1; or y at printf("%d ", y[i]); in the loops with anything other than a value of 0 for i (like x[0] or y[0]) invokes undefined behavior because you would attempt to write to and read from not allocated memory.

"then this means if I don't have any enough buffer, it also will give a segmentation fault for i < 4?"

Exactly. You know that is the bad thing on undefined behavior. It does not need to provide wrong results or errors. So, the i < 4 code is broken, too.

Since you written to "only" 12 bytes after the allocated memory (since sizeof(int) common is 4), it might have worked because there was no other necessary information in memory thereafter, but your code is absolutely broken nonetheless.

-1

you defined less memory than the memory you used causing your program to write after that memory zone and alterate the stack fo the program, this is also the case of the buffer overflow vulnerability in C and C++, increment the buffer size

user695849
  • 23
  • 6