c - 大小为 1 的 Strcpy 读取无效

标签 c valgrind strcpy

我不断收到大小为 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;

}

最佳答案

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

The strtok() and strtok_r() functions return a pointer to the beginning of each subsequent token in the string, after replacing the token itself with a NUL character. When no more tokens remain, a null pointer is returned.

来自你的错误

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

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

关于c - 大小为 1 的 Strcpy 读取无效,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13355217/

相关文章:

c++ - valgrind 提示在 c 中做了一个非常简单的 strtok

c - 执行strcpy时出现段错误

c - strcpy 在 c 中给出段错误

c - 为什么说 vp 和 pf 都在结构节点中时未声明?

c - #define 中的换行符和单双引号

c - 当程序终止时,使用未释放的 malloc 分配的内存会发生什么情况?

c - 什么会将空字符串复制到另一个字符串?

c++ - 标准 C 函数声明语法 (WINAPI)

c - TFT 液晶显示屏速度问题

c - 如何正确发送 time_t 指针到函数?尝试这样做时遇到 valgrind 错误