0

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

3
  • 2
    sizeof(char**) != sizeof(char) Dec 30, 2013 at 13:25
  • 1
    Pointer is 4 bytes of memory. (char**)malloc(10) tries to allocate 2.5 char* positions! Dec 30, 2013 at 13:28
  • 1
    @RikayanBandyopadhyay, it's 4 bytes on a 32 bit architecture. As a rule of thumb, you shouldn't make assumptions on the size of pointers unless you write overly platform specific code. That's what sizeof is for. Dec 30, 2013 at 13:31

1 Answer 1

9
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);
4
  • 2
    And then you should handle the failure case: if (matrix == NULL) { perror("malloc"); exit(EXIT_FAILURE);}; Dec 30, 2013 at 13:27
  • 5
    There is no need to cast mallic/calloc/realloc in C.
    – alk
    Dec 30, 2013 at 13:34
  • 1
    And a comment, that calloc for initializing assumes pointers with all bytes set to 0 to be null pointers.
    – mafso
    Dec 30, 2013 at 13:38
  • @alk: Yes, that's right. I just preferred to point only the fatal error here. But yes, your comment is absolutely correct.
    – anishsane
    Dec 30, 2013 at 13:40

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.