Salman Salman - 1 month ago 11
C Question

Dynamic Array in C

I am using an array and I tried this code:

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

int main()
{
char **q = (char*)malloc(1*sizeof(char*));
q[0]="So Many Books";
q[1]="So Many Books";
q[2]="So Many Books";
q[3]="So Many Books";
q[4]="So Many Books";
printf("%s\n",q[0]);
printf("%s\n",q[1]);
printf("%s\n",q[2]);
printf("%s\n",q[3]);
printf("%s\n",q[4]);
return 0;
}


Why is the compiler not giving me an error here?
I only have booked a place for one string out of an array of strings.

I have looked to some resources like:


Answer

Why is the compiler not giving me an error here

Simply because, the issue here is not related to any syntactical error, it's a logical error that is beyond the jurisdiction of a compiler-error-check.

The problem here is, apart from index 0, any other index is out of bound access here. There is nothing in C standard to stop you from doing that, but accessing out of bound memory invokes undefined behavior, hence the program output is also, undefined. Anything could happen. Just don't do that.

Remember, just because you can do something (write code to access out of bound memory) does not mean you should be doing that.

That said, please see this discussion on why not to cast the return value of malloc() and family in C..