Goutham Panneeru
Goutham Panneeru

Reputation: 165

Segmentation Fault(core dumped) when an int variable is initialized

Segmentation fault appearing due to initializing of the variable 'b'. Someone please help me on this.

#include "stdio.h"
#include "string.h"

int main(){
    char *z[20], *x, *y = {"abcd"};
    int i, j, b = 4;
    for (i = 0 ; i < 4 ; i++) {
         for (j = 0 ; j < b ; j++) {
             *(x + j) = *(y + j + i);
             z[i] = x;
             printf("%s", z[i]);
             printf("\n");
         }
         b--;
    }
    return 0;
}

Upvotes: 2

Views: 1237

Answers (2)

Sourav Ghosh
Sourav Ghosh

Reputation: 134396

You already got the answer from Mr. Iharob for your question, just to elaborate a bit, I though of adding mine.

In your question, you mentioned like

...when an int variable is initialized

This statement is wrong. There is no issue with int variable initializations (i = 0, j = 0 and b = 4). The issue here is with the inappropriate usage of x.

In your code, x is of type char *, i.e., it is a pointer to an char. Now, by saying

 *(x + j) = <some value>

you're trying to assign a value to the char that x (or, rather x + j, in general) points to. Fine, but wait, wait, what does x (or, x + j) actually point to at present?

Answer: x itself is not initialized explicitly, so it does not point to any valid memory where you can write the value. Standards specify, trying to read from or write to an uninitlalized memory location invokes undefined behaviour. Segmentation fault is one of the side effects of UB.

To avoid, you need to allocate memory to x first (so that it points to a valid memory location) and then put the value to the memory location it points to. You can use malloc() and family of functions to get the memory allocation done.

Upvotes: 3

Iharob Al Asimi
Iharob Al Asimi

Reputation: 53026

You dereference x which is not initialized anywhere and hence is an invalid pointer

*(x + j) = *(y + j + i);

Possible solution:

  • Declare x as an array, like

    char x[5];
    

    and, nul terminate it before printing it, like

    x[j]     = y[i + j];
    x[1 + j] = '\0';
    

One more thing, is that every z[i] that is initialized, will point to the same data, i.e. to the array x if you apply my suggested solution.

Upvotes: 5

Related Questions