what am i doing wrong with these pointers

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

testdataunit.c:
Code:
#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:
Code:
testdataunit : testdataunit.c
	gcc -o testdataunit testdataunit.
 
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.
 
solution code, testdatunit.c:
Code:
#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);
}
 
Back
Top