• C

Re-post: Incorrect way to set a string to the empty string causing memory overwrite?

[To all -this is a re-post of my original question which I am about to request be deleted,
since I mis-stated it. Sorry for any confusion :) ]

Given the following

typedef struct {
char     *name;
char     *address;
char      *title;
int        age;
<other elements follow>


I found a statement in some code modified by another programmer as follows:

temp.job_title = "";

with the intent of setting temp.name to the empty string.
This assignment, however, looks WRONG to me. I have always set strings to the empty
string by saying

temp.job_title[0] = 0; (or temp.job_title[0] = '\0';, take your pick).

My suspicion is heightened because of the following. This C file prints a report and
on each line of the report, the string "rogrammer" appears instead of the data I expect
to appear in the first few columns of the report.  Now, it so happens that, right after

temp_job.title = "";

we have

strcpy(temp.job_title, my_job); // where my_job has been set to "Programmer"

I suspect that the following is happening.  The bad assignment statement is setting
the MEMORY ADDRESS of temp_job.title to the memory address of the literal "".
Then the strcpy() is copying my_job ("Programmer") to that location, overwriting
who-knows-what in memory, and corrupting my report.

Am I on the right track here?
Stephen KairysTechnical Writer - ConsultantAsked:
Who is Participating?
Jaime OlivaresConnect With a Mentor Software ArchitectCommented:
This is not valid:
     test.title = "";
     strcpy(test.title, name);

First you assign test.title to a memory position that have room only for 1 byte: the ending null character.
In second like you make a memory violation writing your string to a postion assigned to an unknown data.
Result in unexpected.

Jaime OlivaresSoftware ArchitectCommented:
temp.job_title = "";
is the correct way to assign an empty string to a pointer to a string.
It points to a memory space of 1 byte with content = 0, that is exactly an empty string.

temp.job_title[0] = 0;
This won't work (or at least, should not work), because if the pointer is initially pointing to NULL or to an undefined position, you can't write any value to this position.
But if you have previously assigned a memory position to a buffer to this pointer, then last expression is valid at all, and first expression is unconvenient because you will leave your old buffer "floating" in the memory space without deletion possibility.
Improved Protection from Phishing Attacks

WatchGuard DNSWatch reduces malware infections by detecting and blocking malicious DNS requests, improving your ability to protect employees from phishing attacks. Learn more about our newest service included in Total Security Suite today!

Stephen KairysTechnical Writer - ConsultantAuthor Commented:
But in that case, here's my little test program:

typedef struct
      char *name;
      char *title;
      char flag;

void main()
      TEST test;
      char name[30];

      strcpy(name, "My report");

      test.title = "";
      strcpy(test.title, name);
      printf("%s\n", test.title);

When I run it, the printf() outputs

"y report"
"My report"

which is certainly suspicious. Something is swallowing up the 'M'.

brettmjohnsonConnect With a Mentor Commented:
To put it more clearly:

    test.title = "";
test.title is a POINTER to a character string.  
Here you are pointing it at a 1 character string constant (the empty string).

    strcpy(test.title, name);
Here you attempt to overwrite that 1 character string constant (pointed to by test.title)
with the contents of the name[] array.  This overruns the 1 byte of reserved space,
clobbering other data locations.  

You must have sufficient storage allocated to hold the text you wish to assign.
You almost certainly don't want to overwrite some constant that test.title is pointing to.
You could assign test.title = name;  however both the structure and the buffer go out
of scope when you return from the routine.  And of course, you should not reuse name[]
to store something else while it is acting as the title.
You could modify the structure to contain arrays of char, rather than pointers to char.
(Just be sure to call strncpy() to avoid overflowing the arrays.)
You could allocate more space to hold the string via malloc(), or use strdup() (which calls
malloc for you).  Just remember to deallocate it, via free(), when you are done.
Stephen KairysTechnical Writer - ConsultantAuthor Commented:
Thanks to you both (Jamie and Brett). You both made it very clear that our programmer
was overruning a 1-byte storage.  Now, at least I have a "reason" why this report is failing.

I'm raising the points to 100, and splitting them evenly. I wish I could accept both answers
as the accepted answers, but since Brett provided more detail, he gets the prize<g>.

Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.