简体   繁体   中英

Why this code giving me a segmentation fault?

#include <stdio.h>
int main()
{
    int i,a;
    int* p;
    p=&a;
    for(i=0;i<=10;i++)
    {
        *(p+i)=i;
        printf("%d\n",*(p+i));
    }
    return 0;
}

I tried to assign numbers from 0 to 10 in a sequence memory location without using an array.

a is only an integer. not an array.

you need to declare it differently:

 int i, a[10];

You are trying to write to memory that it does not have permission to access. The variable a is a local variable in the main function, and it is stored on the stack. The pointer p is initialized to point to the address of a. The code then attempts to write to the memory addresses starting at p and going up to p+10. However, these memory addresses are not part of the memory that has been allocated for the program to use, and so the program receives a segmentation fault when it tries to write to them.

To fix this issue, you can either change the loop condition to a smaller value, or you can allocate memory dynamically using malloc or calloc and assign the pointer to the returned address. This will allow you to write to the allocated memory without causing a segmentation fault.

Like this:

#include <stdio.h>
#include <stdlib.h>

int main()
{
int i;
int* p = malloc(sizeof(int) * 11);  // Allocate memory for 10 integers
if (p == NULL) {  // Check for allocation failure
    printf("Error allocating memory\n");
    return 1;
}
for(i=0;i<=10;i++)
{
    *(p+i)=i;
    printf("%d\n",*(p+i));
}
free(p);  // Free the allocated memory when you are done with it
return 0;
}

You can not. Memory of int is 4 bytes and you can store only single number in that memory.

for int: -2,147,483,647 to 2,147,483,647

for unsigned int: 0 to 4, 294, 967 295

There are other types you can use with different sizes, but if you want to put different numbers into one variable you need to use array. int arr[10]; arr[0] = 0; arr[1] = 5; something like this.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM