-1

I am trying the following to assign a value to key, which is part of a stuct. Key is a pointer to a char.

T->oa[i].key = (char*)malloc(5*(sizeof(char)));
strcpy(T->oa[i].key,"abc");

When I run this, I get a seg fault on the strcpy line. What is happening here? Thanks.

Austin
  • 347
  • 7
  • 21

1 Answers1

1

The only way that code segment would be likely to cause a problem is if the malloc actually failed (returning NULL).

Other than that, there should be no issue. Any call that can fail should be checked if it's possible that failure would cause issues later on, and memory allocation followed by de-referencing that memory definitely falls within that description.

A better solution would be something like:

T->oa[i].key = malloc(5);
if (T->oa[i].key == NULL)
    doSomethingIntelligent();
else
    strcpy(T->oa[i].key, "abc");

You'll notice I've also changed the malloc call. In C, it's rarely a good idea to cast the return value from malloc since:

  • the void * returned can be implicitly cast to any other pointer; and
  • it can cause certain subtle errors.

In addition, you never need to multiply by sizeof(char) since that is always, by definition, one.

paxdiablo
  • 854,327
  • 234
  • 1,573
  • 1,953
  • This implementation did the trick. Had no idea that malloc could fail, especially on the one and only call to it in the program. Thanks. – Austin Apr 23 '18 at 05:42
  • @John: wow! I'd consider it *very* unlikely for a single solitary `malloc` to fail in a program unless one of the following is true: (1) rather than only one actual call to `malloc`, you mean there's only a single call but it gets called many *times* without freeing, meaning you'll eventually exhaust memory; (2) you are working in a constrained environment where dynamic memory allocation is disallowed (such as some real-time embedded systems I've worked on); or (3) something else, just to cover all options and make me look more intelligent :-) – paxdiablo Apr 23 '18 at 05:46
  • I myself could not really believe that my hardwired reflex to question anything which ignores return values would actually lead to the solution... – Yunnosch Apr 23 '18 at 05:50