0

I created a 2D character array using malloc and have been trying to assign its values to '\0'.

char **predicate_array = malloc(no_of_lines_in_data_map);
for(int i = 0; i < no_of_lines_in_data_map; i++){
    predicate_array[i] = malloc(1024 * sizeof(char));
    predicate_array[i][0] = '\0';
}

However, when I print the output I get:

predicate_array[0] = (P;

predicate_array[1] = 

predicate_array[2] = 

predicate_array[3] = 

predicate_array[4] = 

predicate_array[5] = 

predicate_array[6] = 

...

...

Would anyone know why the first array is not being set to '\0'?

Thank you.

2 Answers 2

3

the parameter of the first malloc don't fit your 2d-array.

fix it as below

char **predicate_array = (char **)malloc(no_of_lines_in_data_map*sizeof(char *));
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks wy! This appears to have been the problem.
1

Here's the only guess I can hazard. If your no_of_lines_in_data_map is set to 7, which I'm guessing based on the output you are showing, and you are on a 64-bit platform with 8-byte pointers, you haven't allocated enough space for even a single pointer. You allocated 7 bytes, not 7 * size of a pointer bytes.

Likely your program would crash when you try to assign the first malloc, but it doesn't HAVE to, depending on your system and whether or not that memory is allocated to your process. So when you malloc and assign the resulting pointer to the first element of your array, you're assigning to the 7 bytes you expected to, but 1 other byte that is owned by another part of your program. While you set this memory address to the empty string, it's possible that some other part of your program is changing that last byte of your pointer before you print the data at the memory location it's pointing to, sending you at a different memory location for your print statement.

To test this, set no_of_lines_in_data_map to 8 or greater (without fixing anything else) and see if that first bit of output becomes correct (but the program is still broken and you should expect it to either crash or give bad data elsewhere, still).

To fix it permanently, do what vvy suggested (except don't cast your malloc).

Also, the pedant in me wants to say you're not really allocating a 2D array, as the memory isn't contiguous. You're really allocating an array pointing to a list of arrays, but they're spread out all over.

1 Comment

Appreciate the explanation xaxxon!

Your Answer

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