Pedro R.
Pedro R.

Reputation: 93

Char Pointer allocation within a function - Segmentaion fault

I am trying to allocate memory to a char pointer inside a function. But I get a segmentation fault inside the function in the for cycle at i=1. For i=0it allocates memory. I am struggling to get this solved. Maybe other 'eyes' can see what is wrong.

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

void AllocateDeallocate(int, int, int, char***);

int main(void)
{
    char** header1;
    char** header2;
    AllocateDeallocate(1,3,40,&header1);

    return 0;
}

void AllocateDeallocate(int iopt, int nStr, int StrLen, char*** Str)
{
    int i;
    switch (iopt)
    {
    case 1:
        if (NULL == Str)
        {           
            exit(EXIT_FAILURE);
        }
        if(*Str == NULL)
        {
            *Str = (char**)malloc(sizeof(char*)*nStr);          
            if (*Str== NULL)
            {
                puts("Memory allocation failed.");
                exit(EXIT_FAILURE);
            }       
        }
        for(i = 0 ; i< nStr;i++)
        {   
            printf("String %d allocation\n",i); 
            *Str[i] = (char*)malloc(sizeof(char)*(StrLen+1));
            if (*Str[i] == NULL)
            {
                puts("Memory allocation failed.");
                exit(EXIT_FAILURE);
            }
        }
        break;
    case 2:
        for( i = 0; i<nStr; i++)
        {
            free(*Str[i]);
        }
        free(*Str);
        break;
    default:
        printf("Wrong Option");
    }
}   

Upvotes: 0

Views: 78

Answers (1)

Some programmer dude
Some programmer dude

Reputation: 409176

When you call the function AllocateDeallocate the variable header1 is not initialized. That means inside the function *Str haven an indeterminate value (and will be seemingly random).

When you then use *Str (for example in *Str == NULL) that will lead to problems (as the value is most likely not equal to NULL).

The simple solution? Initialize the variables in the main function:

char** header1 = NULL;
char** header2 = NULL;

Once you fix the above problem you have others. Like when you do *Str[i]. Due to operator precedence rules it's equal to *(Str[i]) which is not what you want. You need to explicitly use parentheses to have (*Str)[i].


Both the above problems will lead to undefined behavior and are likely causes for crashes.

Upvotes: 3

Related Questions