【问题标题】:Access violation reading location 0x00000000. with argv[]访问冲突读取位置 0x00000000。与 argv[]
【发布时间】:2013-06-06 04:03:35
【问题描述】:

我正在运行以下程序并出现错误:

First-chance exception at 0x0f32d440 (msvcr100d.dll) in c.exe: 0xC0000005: Access violation reading location 0x00000000.
Unhandled exception at 0x772815de in c.exe: 0xC0000005: Access violation reading location 0x00000000.
The program '[9048] c.exe: Native' has exited with code -1073741510 (0xc000013a).

这里是代码

#include <string.h>
#include <stdio.h> 
#include <stdlib.h> 
int main(int argc, char *argv[], char *env[]) //char *argv[] 
{ 
int i; 

printf("These are the %d command- line arguments passed to main:\n\n", argc); 
if(strcmp(argv[1],"123")==0)                
    {
        printf("success\n");
     }
else
for(i=0; i<=argc; i++) 
    //if(strcmp(argv[1],"abc")==0)

    printf("argv[%d]:%s\n", i, argv[i]);
/*printf("\nThe environment string(s)on this system are:\n\n"); 
for(i=0; env[i]!=NULL; i++) 
printf(" env[%d]:%s\n", i, env[i]);*/ 
system("pause");
} 

问题应该出在 strcmp 函数上,但我不知道如何解决。 有人可以帮忙吗?

【问题讨论】:

    标签: c pointers access-violation argv strcmp


    【解决方案1】:

    你有(至少)两个问题。

    首先是这样做的:

    if(strcmp(argv[1],"123")==0) 
    

    没有先检查argc &gt;= 2

    第二个是这样的:

    for(i=0; i<=argc; i++) 
    

    因为你应该处理参数0 thru argc - 1 包括在内。该循环所做的是处理参数0argcargv[argc] 始终是NULL

    以下程序说明了解决此问题的一种方法:

    #include <stdio.h>
    #include <stdlib.h>
    #include <string.h>
    
    int main (int argc, char *argv[]) {
        int i;
    
        printf ("These are the %d command-line argument(s) passed to main:\n", argc);
        if ((argc >= 2) && (strcmp (argv[1], "123") == 0)) {
            printf ("   success\n");
        } else {
            for (i = 0; i < argc; i++)  {
                printf ("   argv[%d] = [%s]\n", i, argv[i]);
            }
        }
        return 0;
    }
    

    您可以看到与"123" 的比较仅在确保正确填充argv[1] 后完成。此外,循环已更改为排除 argv[argc],因为这不是参数之一。成绩单如下:

    pax> testprog
    These are the 1 command-line argument(s) passed to main:
       argv[0] = [testprog]
    
    pax> testprog 123
    These are the 2 command-line argument(s) passed to main:
       success
    
    pax> testprog a b c
    These are the 4 command-line argument(s) passed to main:
       argv[0] = [testprog]
       argv[1] = [a]
       argv[2] = [b]
       argv[3] = [c]
    

    【讨论】:

      【解决方案2】:

      for(i=0; i&lt;=argc; i++) 应该是for(i=0; i&lt;argc; i++)

      C/C++ 数组是 0 到 n-1。您正在从阵列末端跑出 1 个位置。

      【讨论】:

      • 还要确保在您的第二个数组 argv 中实际上有超过 1 项您当前在 argv[1] 处引用数组中的第二项,可能应该是 argv[0]
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-08-28
      • 1970-01-01
      • 2013-04-15
      相关资源
      最近更新 更多