0

I'm new to c and I have the following problem:

after executing this part of the code

TypeDefStruct tdss[10];
for(...) {
        TypeDefStruct *tds = (TypeDefStruct*)malloc(sizeof(TypeDefStruct));
        strcpy(&tds->data, charPointerArray[index]) // works (not original code)
        memcpy((void*) &tdss[index], (void*) &tds, sizeof(TypeDefStruct)); // new
        free(tds);  // new
    }

an error occurs here

TypeDefStruct *tds = &tdss[0]; // worked before
printf("\twith input: \"%s\"\n", tds->data); // worked before

the TypeDefStruct:

typedef struct TypeDefStruct{
    char* data;
} TypeDefStruct;

also the error sigsagv occurs at some point (don't know where, may not here at all...)

what I'm trying to do

I am trying to copy this struct into an array and manage my memory correctly.

please, don't mind asking for more information!

5
  • The problem with undefined behavior (which you have) is that sometimes it might seem to work. Commented May 13, 2015 at 17:35
  • I have two pieces of advice for you: 1) valgrind is the best available tool for diagnosing what has actually gone wrong in cases of memory corruption. It is very common for the true cause of such bugs to be nowhere near the point where the program crashes. 2) For us to help you, we need a minimal, complete, verifiable example -- a complete program, that we can run for ourselves and watch crash, containing no more code than is strictly necessary to reproduce the problem. You may discover the bug yourself while writing this. Commented May 13, 2015 at 17:36
  • And a third, unrelated piece of advice: TypeDefStruct is a terrible name for a data type. Think of something more meaningful. Commented May 13, 2015 at 17:37
  • thanks for your advices! the names are changed like some people do with foo, bar. And the program is huge. this will take a while. Commented May 13, 2015 at 17:43
  • I think i got a part of my problem figured out. memcpy((void*) &tdss[index], (void*) &tds, sizeof(TypeDefStruct)); // new has a syntax error! Since tds is a type defined struct we don't need the & Commented May 13, 2015 at 18:38

2 Answers 2

2
strcpy(&tds->data, charPointerArray[index]) // works (not original code)

data is an uninitialized object, you need to allocate an array with malloc. Also &tds->data argument is wrong, you need to use tds->data.

Sign up to request clarification or add additional context in comments.

1 Comment

@SteveMcGregor people will only comment on the code your posted; moreover the & error is serious.
0

In my case this did not solve all my errors. Also not the sigsegv.

But there is a Syntax error in

memcpy((void*) &tdss[index], (void*) &tds, sizeof(TypeDefStruct)); !

Since tds is a type defined struct we don't need the &. At least I think so...

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.