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

Posted on 2004-09-28
Medium Priority
Last Modified: 2010-04-15
[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?
Question by:Stephen Kairys
LVL 55

Expert Comment

by:Jaime Olivares
ID: 12175462
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.
LVL 22

Expert Comment

ID: 12175469

Author Comment

by:Stephen Kairys
ID: 12175562
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'.

Independent Software Vendors: We Want Your Opinion

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

LVL 55

Accepted Solution

Jaime Olivares earned 200 total points
ID: 12175672
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.

LVL 23

Assisted Solution

brettmjohnson earned 200 total points
ID: 12175979
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.

Author Comment

by:Stephen Kairys
ID: 12176059
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>.


Featured Post


Modern healthcare requires a modern cloud. View this brief video to understand how the Concerto Cloud for Healthcare can help your organization.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

An Outlet in Cocoa is a persistent reference to a GUI control; it connects a property (a variable) to a control.  For example, it is common to create an Outlet for the text field GUI control and change the text that appears in this field via that Ou…
Preface I don't like visual development tools that are supposed to write a program for me. Even if it is Xcode and I can use Interface Builder. Yes, it is a perfect tool and has helped me a lot, mainly, in the beginning, when my programs were small…
The goal of this video is to provide viewers with basic examples to understand and use structures in the C programming language.
The goal of this video is to provide viewers with basic examples to understand how to use strings and some functions related to them in the C programming language.
Suggested Courses

840 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question