Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Mike Lewis on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

StringCopy Help 1

Status
Not open for further replies.

madprince

Programmer
Nov 6, 2003
2
0
0
US
I am new to C and want to know why this program adds garbage at the end of the string.

#include <stdio.h>
#include <stdlib.h>


char* cpy(char*);
int main() {
char *old = &quot;Hello All Now i thought this would work apparently&quot;;
char *newer = cpy(old);
printf(&quot;%s&quot;,newer);
getchar();
return 1;
}

char* cpy(char* old) {
char* newer = (char*)malloc(sizeof(old)-1) ;
int i = 0;
while(old != '\0')
newer = old[i++];
return newer;
}
 
It did not get copied properly the function is

char* cpy(char* old) {
char* newer = (char*)malloc(sizeof(old)-1) ;
int i = 0;
while(old != '\0')
newer[ i ] = old[i++];
return newer;
}
 
Code:
 while(old[i]!= '\0')
        newer[ i ] = old[i++];
 newer[i]='\0';
u'll have to terminate ur new string with '\0'
 
This statement is the culprit:-

char* newer = (char*)malloc(sizeof(old)-1) ;

see the problem is that you have a declared a string literal
&quot;Hello All Now i thought this would work apparently&quot;

It is residing at some memory location say starting from 0x1000 in the memory. Now you have a pointer 'old' that points to this location. When you pass it on to the function cpy(), a copy of the 'old' is created and given as a parameter to the cpy().

This parameter old(of the cpy function) is also pointing to the orginal string. But as such it is just a pointer and not an array of its own. So when you do

sizeof(old), this will return 4/2 depending on the word size of the machine. Like on Intel PC it gave me 4. Whereas your actual string is much longer than 4.

To calculate the string length call strlen() and not sizeof().


 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top