-1

This when compiling results in a segmentation fault (core dumped).

char buffer[7];

// Create an array to store plate numbers
char *plates[8];

FILE *infile = fopen(argv[1], "r");

int idx = 0;

while (fread(buffer, 1, 7, infile) == 7)
{
    // Replace '\n' with '\0'
    buffer[6] = '\0';

    // Save the plate number in the array
    plates[idx] = strcpy(plates[idx], buffer);
    idx++;
}

I was just wondering why can't I use memory directly from pointer plates to store strcpy() with allocating a specific size memory to plates[idx] first.

// Create a buffer to read into
char buffer[7];

// Create an array to store plate numbers
char *plates[8];

FILE *infile = fopen(argv[1], "r");

int idx = 0;

while (fread(buffer, 1, 7, infile) == 7)
{
    // Replace '\n' with '\0'
    buffer[6] = '\0';

    // Save plate number in array
    plates[idx] = malloc(sizeof(char) * 7);
    plates[idx] = strcpy(plates[idx], buffer);
    idx++;
}
Trying90
  • 1
  • 1

1 Answers1

0

plates is an array of char *, i.e., pointers. Unless you make them point to some valid memory location (like in the second snippet), the location they point to is going to be invalid from the point of view of your application.

Attempt to write to invalid memory location (like in the first snippet) invokes undefined behaviour, and segmentation fault is one side effect of undefined behaviour.

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