1

Given the following code, is it legal in C? (C89, C99, and so on?)

DATA_STRUCT *ptr;

ptr = malloc(sizeof(*ptr) + 400);

memset(ptr, 0, sizeof(*ptr)); // clearing only the structure itself (not the 400 additional bytes).

I'm aware of VLA and sizeof being evaluated at run-time, but for all other cases, is it always at compile-time?


EDIT: From the answers I see this may be caused by:

  1. A compiler bug
  2. A heap corruption

1 seems sorta unlikely, so I'm leaning towards 2. Either way, this needs to be further investigated.

Jimmy Lu
  • 4,810
  • 7
  • 25
  • 30
  • This was just asked [why sizeof(x++) does not increment the variable x value](http://stackoverflow.com/questions/21995680/why-sizeofx-does-not-increment-the-variable-x-value), and the answer is the same, it is unevaluated. – Shafik Yaghmour Feb 24 '14 at 19:13
  • @BLUEPIXY well the last sentence asks `I'm aware of VLA and sizeof being evaluated at run-time, but for all other cases, is it always at compile-time?` which is basically the same question. – Shafik Yaghmour Feb 24 '14 at 19:16
  • The call to malloc is wrong, malloc takes one parameter only. But `sizeof(x)` will never evaluate x, so your code is ok. – Guntram Blohm Feb 24 '14 at 19:16

2 Answers2

0

Yes, your code is legal. The parentheses around *ptr aren't necessary, though.

Carl Norum
  • 219,201
  • 40
  • 422
  • 469
  • thanks, I also thought so. But we're seeing a bug right now that the program crashes at this line (changing *ptr to DATA_STRUCT) solves the problem). And it's certainly not a VLA. This is weird... Needs further investigation on our part... maybe somewhere else in the code is blowing up... – Jimmy Lu Feb 24 '14 at 19:16
  • ... Or your compiler is nonstandard, possibly. – Carl Norum Feb 24 '14 at 19:19
  • @BeyondSora: Which "this line"? The malloc or the memset? Did you leave out the line where you check if the malloc returns NULL, or is it not there? – rici Feb 24 '14 at 19:29
  • 1
    @BeyondSora: I seriously doubt that changing `sizeof(*ptr)` to `sizeof(DATA_STRUCT)` solved the problem. Recompiling may have caused *different* randomish behavior to occur. If your program crashes on a call to `malloc`, it's probably because something that executed previously corrupted the heap. Run the program under `valgrind` if possible. (And since your real problem is that your program crashes, you probably should have asked about that rather than about the legality of `sizeof(*ptr)`.) – Keith Thompson Feb 24 '14 at 19:30
  • @KeithThompson thanks. This question was probably phrased in a wrong way. I didn't doubt that sizeof(*ptr) was the problem and suspected something else was going on. But since the bug is temporarily "suppressed" I thought to ask on StackOverflow to clarify the legality of sizeof(*ptr) before the team proceeds to root cause further. – Jimmy Lu Feb 24 '14 at 19:41
0

Yes, it is valid. sizeof operator does not evaluate its operand.

ouah
  • 142,963
  • 15
  • 272
  • 331