gpt4 book ai didi

scanf() 损坏的 malloc 区域

转载 作者:行者123 更新时间:2023-11-30 14:22:56 25 4
gpt4 key购买 nike

我的代码有问题:

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
typedef struct hashTable{
char *data;
struct hashTable *next;
}HASHTABLE;

HASHTABLE **linkedHashTable[100];
void SaveHashTable1(char *str2,char *str3) //s retazenim---Linked List
{
int hashResult;
HASHTABLE* linkedHashTableNode=NULL, *new_;

hashResult=StringToInt(str2);

if(linkedHashTable[hashResult]==NULL)
{
linkedHashTableNode=(HASHTABLE*)malloc(sizeof(HASHTABLE));

linkedHashTableNode->data=(char*)malloc(strlen(str3)*sizeof(char));
strcpy(linkedHashTableNode->data,str3);

linkedHashTableNode->next=NULL;
linkedHashTable[hashResult]=&linkedHashTableNode;
}
else
{
linkedHashTableNode=*linkedHashTable[hashResult];
while(linkedHashTableNode->next!=NULL)
linkedHashTableNode=linkedHashTableNode->next;

new_=(HASHTABLE*)malloc(sizeof(HASHTABLE));

new_->data=(char*)malloc(strlen(str3)*sizeof(char));
strcpy(new_->data,str3);
new_->next=NULL;
linkedHashTableNode->next=new_;
}

}
int main(void)
{
char *str1=NULL, *str2=NULL, *str3=NULL;
int i;


while(1)
{
scanf("%s ", str1);
if((strcmp(str1, "save"))==0) //SAVE
{
scanf("%s %[^\n]s", str2, str3);

SaveHashTable1(str2, str3);
}
}
}

这是代码的一部分,当我尝试执行此操作时,我遇到了问题:

linkedHashTableNode->data=(char*)malloc(strlen(str3)*sizeof(char));
strcpy(linkedHashTableNode->data,str3);

我总是在scanf()的内存区域附近获得内存空间,所以当我再次从控制台读取数据时,原始数据会被重写。我不知道哪里会出现问题。

感谢您的帮助。

最佳答案

您没有在 malloc 调用中请求足够的内存。 strlen 告诉您字符串中有多少个字符,不包括终止 NUL,但 strcpy 无论如何都会复制终止 NUL 字符。

关于scanf() 损坏的 malloc 区域,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13348687/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com