使用strcpy无效写入

时间:2012-12-28 20:32:14

标签: c memory-leaks valgrind

我已经编程了一段时间,但我是C的新手。我在ansi C中有这个链接列表实现,我需要测试。我已将问题缩小到写入无效的问题。我通过Valgrind运行代码并收到以下输出:

==18131== Invalid write of size 1
==18131==    at 0x4C2C0CC: __GI_strcpy (in /usr/lib/valgrind/vgpreload_memcheck-amd64 linux.so)
==18131==    by 0x40089B: main (in /home/btm7984/hw3/TestList)
==18131==  Address 0x51f1388 is 0 bytes after a block of size 8 alloc'd
==18131==    at 0x4C2B6CD: malloc (in /usr/lib/valgrind/vgpreload_memcheck-amd64-linux.so)
==18131==    by 0x400880: main (in /home/btm7984/hw3/TestList)
==18131==
==18131== Invalid write of size 1
==18131==    at 0x4C2C0DF: __GI_strcpy (in /usr/lib/valgrind/vgpreload_memcheck-amd64-linux.so)
==18131==    by 0x40089B: main (in /home/btm7984/hw3/TestList)
==18131==  Address 0x51f138e is 6 bytes after a block of size 8 alloc'd
==18131==    at 0x4C2B6CD: malloc (in /usr/lib/valgrind/vgpreload_memcheck-amd64-linux.so)
==18131==    by 0x400880: main (in /home/btm7984/hw3/TestList)
==18131==
--18131-- VALGRIND INTERNAL ERROR: Valgrind received a signal 11 (SIGSEGV) - exiting
--18131-- si_code=1;  Faulting address: 0x6D4FCAA;  sp: 0x402bdae00

我可以从中确定的一点是,我分配错误的东西。我认为必须与我的strcpy线。我真的不知道如何处理这个问题。接下来是我对LinkedLists接口的使用。 InitLinkedLists,AddToBackOfList和DestroyList都在该接口中定义。

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "LinkedLists.h"

int main(int argc, char *argv[]) {

  FILE *fp;
  char tmpString[100];
  LinkedLists *ListPtr = malloc(sizeof(LinkedLists));
  ElementStructs *DataPtr;
  LinkedListNodes* curr = malloc(sizeof(LinkedListNodes));
  int counter = 0;
  int Done = 0;

  InitLinkedList(ListPtr);
  fp = fopen(argv[1], "r");
  if (!fp){
    fprintf(stderr,"%s Cannot open file %s\n", argv[0], argv[1]);
    exit(1);
  }
  do{
    fscanf(fp,"%s",tmpString);
    if (!feof(fp)) {
      DataPtr = malloc(sizeof(DataPtr));
      printf("%d   %d : %d\n",counter,(int)strlen(DataPtr->str),(int)strlen(tmpString));
      strcpy(DataPtr->str,tmpString);
      DataPtr->index=counter;
      AddToBackOfLinkedList(ListPtr, DataPtr);
      counter++;
      Done = 1;
    } else {
      Done = 0;
    }
  }while (Done);

总之,我认为strcpy导致写入无效,我不知道为什么。

非常感谢任何帮助。提前谢谢。

编辑:ElementStructs定义如下:

typedef struct ElementStructs
   {
   /* Application Specific Definitions */
   int index;
   char str[100];
  } ElementStructs;

1 个答案:

答案 0 :(得分:3)

问题在于这句话:

DataPtr = malloc(sizeof(DataPtr));

您只分配足够的内存来保存指针而不是完整的结构。

您应该使用:

进行分配
DatapPtr = malloc(sizeof(ElementStructs));

或者,如评论(WhozCraig)中所述:

DatapPtr = malloc(sizeof(*DataPtr));