开发者

scanf segfaults and various other anomalies inside while loop

while(1){
    //Command prompt
    char *command;
    printf("%s>",current_working_directory);
    scanf("%s",command);<--seg faults after input has been received.
    printf("\ncommand:%s\n",command);
}

I am getting a few different errors and they don't really seem reproducible (except for the segfault at this point). This code worked fine about 10 minutes ago, then it infinite looped the printf command and now it seg faults on the line mentioned above. The only thing I changed was scanf(">%s",command); to what it currently is. If I change the command variable to be an array it works; obviously this is because the storage is set aside for it.

  1. I got prosecuted about telling someone that they needed to malloc a pointer* (but that usually seems to solve the problem such as making it an array)
  2. The command I am entering is "magic" -- 5 characters -- so there shouldn't be any crazy stack overflow.
  3. I am running on Mac OS X 10.6 with newest version of xCode (non-OS4) and standard gcc
  4. This is how I compile the program: gcc --std=c99 -W sfs.c

Just trying to figure out what is going on. Since this is for a school project I am never going to have to see again, I will just code some noob work around that would make my boss cry :) But for afterwards I would love to 开发者_Go百科figure out why this is happening and not just make some fix for it, and if there is some fix for it why that fix works.


scanf tries to store the data it reads into the argument (command in your case). That variable has not been initialized to point to valid memory. The malloc to assign memory to it would, therefore, make it valid. It could also be declared on the stack:

char command[somearraysize];


 char command[100];
 scanf("%s",command);

As to why this is necessary, I suggest reading a book on C, such as The C Programming Language.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜