# what am i doing wrong with these pointers



## lockfile (Oct 20, 2012)

After I declare the key1 structure, I can't set it's member *dptr. I have been working on this since yesterday 

testdataunit.c:

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

typedef struct {
  char *dptr;
  int dsize;

} datum;

int main(int argc, char* argv[]) {
  char keychar = 'b';
  datum key1;   
  printf("debug: char set in key1\n");

  char cpystring[] = "hey this is my string";
  key1.dptr = cpystring; // this causes the crash!!!
  printf("debug: cpystring allocated\n");
 
  exit(0);
}
```

Makefile:

```
testdataunit : testdataunit.c
	gcc -o testdataunit testdataunit.
```


----------



## lockfile (Oct 20, 2012)

Found the problem in source code of testgdbm.c in the GNU gdbm library.. I had to use strdup() rather than strcpy() as strcpy() arg 1 is expected to be a pointer while I was passing a reference. The segfault was the result.


----------



## lockfile (Oct 20, 2012)

solution code, testdatunit.c: 

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

typedef struct {
  char *dptr;
  int dsize;

} datum;

int main(int argc, char* argv[]) {
  char keychar = 'b';
  datum key1;   
  printf("debug: char set in key1\n");

  char cpystring[] = "hey this is my string";
  key1.dptr = &cpystring[0];
key1.dptr =  strdup(&cpystring[0]); // no segfault occurs, can now printf() :)
  printf("debug: string copied\n");
 
  exit(0);
}
```


----------

