【问题标题】:Invalid read of size 1 Strcpy大小为 1 的无效读取 Strcpy
【发布时间】:2012-11-01 13:20:15
【问题描述】:

我不断收到大小为 1 的无效读取的 valgrind 错误,我无法确定原因。

是什么导致了错误?

==24647== Invalid read of size 1
==24647==    at 0x40258EA: strcpy (mc_replace_strmem.c:437)
==24647==    by 0x8048606: main (source.c:26)
==24647==  Address 0x0 is not stack'd, malloc'd or (recently) free'd
==24647==
==24647==
==24647== Process terminating with default action of signal 11 (SIGSEGV)
==24647==  Access not within mapped region at address 0x0
==24647==    at 0x40258EA: strcpy (mc_replace_strmem.c:437)
==24647==    by 0x8048606: main (source.c:26)
==24647==  If you believe this happened as a result of a stack
==24647==  overflow in your program's main thread (unlikely but
==24647==  possible), you can try to increase the size of the
==24647==  main thread stack using the --main-stacksize= flag.
==24647==  The main thread stack size used in this run was 16777216.

下面是我的代码,我评论了检测到错误的行 (source.c:26)。

#include <stdio.h>
#include <stdlib.h>
#include <limits.h>
#include <string.h>

int main()
{

    char input[100];

    char name[100];

    char age[100];

    int agee[100];

    fgets(input,sizeof(input),stdin); //i scan in the string and store int char array called input.

    char *charpoint;//declare pointer character

    charpoint=strtok(input,"\"");//run strtoken with quotation marks as second part of argument.

    strcpy(name,charpoint);

    char * charpoint2=strtok(NULL,"\",");

    strcpy(age,charpoint2); //This line is where the error occurs. line 26

    sscanf(age,"%d",&agee[0]);

    printf("%s %d",name, agee[0]);

    system("pause");

    return 0;

}

【问题讨论】:

  • 程序的输入是什么?
  • 输出应该是 John, Smith 55

标签: c valgrind strcpy


【解决方案1】:

来自手册页(强调我的):

strtok() 和 strtok_r() 函数返回一个指向开头的指针 在替换标记本身之后,字符串中的每个后续标记 带有 NUL 字符。 当没有更多标记时,空指针是 返回。

你的错误

==24647==  Address 0x0 is not stack'd, malloc'd or (recently) free'd

所以你的指针charpoint2 是NULL,这意味着你之前的strtok 调用没有找到你期望的。您应该检查这种可能性并打印有关输入格式的错误。当然,您应该验证您的 strtok 调用是否符合您的预期。

【讨论】:

    【解决方案2】:

    关于你的程序的几件事。

    1. 使用前清除所有数组,这样可以确保没有读入垃圾。您可以使用 memset 或仅使用 char input[100] = {0};
    2. 读入数据后,通过显式设置 input[99] = '\0' 确保输入为空终止。这是为了确保输入永远不会超过数组的大小
    3. 对 strtok 返回的指针进行空值检查,不能保证您得到预期的结果。适当地处理空值。我的预感是 charpoint2 会为您返回 null,因此会出现错误。

    【讨论】:

      猜你喜欢
      • 2014-11-30
      • 2020-08-19
      • 2014-04-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-11-17
      • 2020-09-30
      相关资源
      最近更新 更多