AlbertoZ
AlbertoZ

Reputation: 164

malloc, allocating a matrix

I allocate a vector of strings in this way:

    int number =0;
    char** matrix = (char**)malloc(10);
    //when I have to allocate a string, use 
    matrix[number] = (char*)malloc(lenght_of_string);
    number++; //MAX 10

Ok, I want that the vector has a null pointer when there's no string, so I can use calloc:

    int number =0;
    char** matrix = (char**)calloc(10,1);
    //when I have to allocate a string, use 
    matrix[number] = (char*)malloc(lenght_of_string);
    number++; //MAX 10

But, if I do not want to use calloc, and use malloc instead, inizializing all the pointer values to null, why I get a SIGABRT signal on linux?

    nt number =0;
    char** matrix = (char**)malloc(10);
    for (i=0;i<10;i++)
        matrix[i] = NULL;
    //when I have to allocate a string, use 
    matrix[number] = (char*)malloc(lenght_of_string);    //ERROR: SIGABRT
    number++; //MAX 10

I think that in the for cicle I overwrite some special informations about the memory allocated, can someone explain me what it happen?


Thank you anishsane, you are right, but sometimes I don't respect rules. So bad...anyway, sizeof(char) returns 1, so in this example it's the same to write 10*sizeof(char) and only 10. Why in the calloc function you pass first the size of char and then the number of chars? I read here: http://www.cplusplus.com/reference/cstdlib/calloc/ and I should pass first the number of chars and then the sizeof

Upvotes: 0

Views: 1203

Answers (1)

anishsane
anishsane

Reputation: 20980

char** matrix = (char**)malloc(10);

Should be

char** matrix = (char**)malloc(10*sizeof(char*));

Also,

char** matrix = (char**)calloc(10,1);

Should have been

char** matrix = (char**)calloc(sizeof(char*),10);

Upvotes: 9

Related Questions