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

Posted on 2004-09-28
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 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'.

ScreenConnect 6.0 Free Trial

Explore all the enhancements in one game-changing release, ScreenConnect 6.0, based on partner feedback. New features include a redesigned UI, app configurations and chat acknowledgement to improve customer engagement!

LVL 55

Accepted Solution

Jaime Olivares earned 50 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 50 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

Efficient way to get backups off site to Azure

This user guide provides instructions on how to deploy and configure both a StoneFly Scale Out NAS Enterprise Cloud Drive virtual machine and Veeam Cloud Connect in the Microsoft Azure Cloud.

Question has a verified solution.

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

Suggested Solutions

Windows programmers of the C/C++ variety, how many of you realise that since Window 9x Microsoft has been lying to you about what constitutes Unicode ( They will have you believe that Unicode requires you to use…
This is a short and sweet, but (hopefully) to the point article. There seems to be some fundamental misunderstanding about the function prototype for the "main" function in C and C++, more specifically what type this function should return. I see so…
Video by: Grant
The goal of this video is to provide viewers with basic examples to understand and use for-loops in the C programming language.
Video by: Grant
The goal of this video is to provide viewers with basic examples to understand and use while-loops in the C programming language.

861 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

Need Help in Real-Time?

Connect with top rated Experts

28 Experts available now in Live!

Get 1:1 Help Now