warning: format ‘%d’ expects type ‘int *’, but argument 2 has type ‘int’

前端 未结 7 1751
醉话见心
醉话见心 2020-12-09 20:39

So I\'m new to C and am having trouble with whats happening with this warning. What does the warning mean and how can i fix it. The code i wrote is here:

voi         


        
7条回答
  •  有刺的猬
    2020-12-09 21:01

    The problem is this line:

    scanf("%d\n", age);
    

    scanf expects pointer arguments - this is the only way functions can modify parameters in C. In order to fix this one, you need to:

    scanf("%d\n", &age);
    

    Which passes the addressof age, which is now a pointer (a pointer is a variable containing an address to another area of memory).

    As for this:

    char* name = "";
    

    Ouch-ow-please-don't! Ok, I need to explain. You've asked for a pointer to a character type, but as far as everyone's concerned, all you've got is a character, not a whole string. That's right, not enough space. Why does C let you do this? Well, C is basically portable assembler, so you can write wherever you like in memory (or rather, you can try and the compiler won't disagree, but the operating system can and probably will).

    What you need to do is read up on memory allocation using malloc in order to allocate some space, otherwise I can input a massive string and it gets put at the address of name onwards.

    This can, although by no means will, lead to stack-based vulnerabilities. What, stacks? Yes. A stack is a FILO structure and every time you call a function, you add space onto the stack for your return address and function arguments, as well as frequently function-scope variables.

    Where this becomes a problem is if you don't check input sizes. Then, I can write massive values to your stack, including executable code... see Buffer Overflow.

    So how do I mitigate this, I hear you say, just yearning not to implement software vulnerabilities? You use functions that allow you to specify your buffer input size and read into a buffer of a specific size, and go from there. That's it. That simple.

    See this question: string reading in C.

提交回复
热议问题