1

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:

8
  • There's no syntax errors, so no compiler errors. In c, memory management is up to the programmer. Sounds like you already know your code is rife with UB. Commented Oct 28, 2016 at 19:20
  • You're a C programmer. You're assumed to know what you're doing. If you want hand-holding, choose a different language. That makes it tough on beginners in particular, but the mindset is "the programmer knows what they're doing", even when it is manifest that they don't. Commented Oct 28, 2016 at 19:22
  • 4
    Why are you casting the result of malloc to char *, when you need a char **? Why are you casing the result of malloc at all??? Commented Oct 28, 2016 at 19:23
  • The compiler doesn't know that you haven't allocated enough memory; that's a problem that doesn't show up until compile time. A sufficiently clever compiler might be able to figure it out, but in general the argument passed to malloc needn't be a compile-time constant, and it's not possible to detect this kind of error in all cases. Commented Oct 28, 2016 at 19:24
  • is not about handd-holding ,, but should't stop ?cus i am assigning in un booked place ? Commented Oct 28, 2016 at 19:25

1 Answer 1

2

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..

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.