NukPan
NukPan

Reputation: 319

Segmentation Fault char** after malloc

I want ** char finalString, i.e. a list of *char. After my function runs, each *char pointer contains a char 'A', 'B', 'C', which can then be passed to a function expecting a parameter of type char**. Each string has to be separate, but in the same array, hence the **.

Creating this **char, I wrote the following:

char ** finalString;
finalString = malloc(sizeof(char*)*3);
int stringAddressCounter = 0;

Then, to add a char to this, I tried the following:

char ** nextStringAddress = finalString + stringAddressCounter;
** nextStringAddress = 'A';
stringAddressCounter++;

However, I'm getting a segmentation fault on the second line of this block.

What am I doing wrong?

Upvotes: 0

Views: 55

Answers (1)

SaltyPleb
SaltyPleb

Reputation: 353

You allocated memory for your char* , but did not allocate memory for your char to be stored.

Here's a thumb rule for pointer, each * should have a malloc that means for char ** you should have one malloc for char * and another one for char.

also playing with pointer is a bit misleading sometimes and bracket should be used instead for readability

char ** nextStringAddress = finalString + stringAddressCounter;
nextStringAddress[stringAddressCounter] = malloc(sizeof **nextStringAddress * 3)
nextStringAddress[stringAddressCounter][0] = 'A';
nextStringAddress[stringAddressCounter][1] = 'a';
nextStringAddress[stringAddressCounter][2] = '\0';
stringAddressCounter++;

Doing with a single malloc is also possible like so

char ** nextStringAddress = finalString + stringAddressCounter;
nextStringAddress[stringAddressCounter] = "Aa";
stringAddressCounter++;

Notice the double quote here around the Aa and the missing second bracket. It should be noted that by doing this, you are essentially assigning a memory zone that is read only, and by trying to assign on this memory, it will result in a segmentation fault.

Upvotes: 1

Related Questions