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 SkipVought on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

atoi problem 1

Status
Not open for further replies.

maur3r

Technical User
Aug 28, 2006
34
0
0
PL
I have got a problem with atoi function. From definition it converts string to intiger and as an argument it takes const char*. int atoi (const char *nPtr). If so why this code is wrong
Code:
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
int main()
{
char *data;
int i,r;
data=malloc(10);
for (i=0;i<10;i++)
data[i]='1';
printf("%s\n",data);
return 0;
r=atoi(data);
}
When I use valgrind I receive:
Code:
==8663== Invalid read of size 1
==8663==    at 0x1B9413F8: (within /lib/tls/libc-2.3.5.so)
==8663==    by 0x1B9410CE: __strtol_internal (in /lib/tls/libc-2.3.5.so)
==8663==    by 0x1B93E6E5: atoi (in /lib/tls/libc-2.3.5.so)
==8663==    by 0x804843B: main (test.c:11)
==8663==  Address 0x1BA48032 is 0 bytes after a block of size 10 alloc'd
==8663==    at 0x1B8FF896: malloc (vg_replace_malloc.c:149)
==8663==    by 0x804840D: main (test.c:8)
I need to use atoi in such situation in larger project therefore I will apprecciate any kind of help.
Thanks in advance.

Martin
 
1) Your string is not terminated i.e. after your loop

data[9] = 0;

2) Your atoi appears after the return so I don't know how your program produces the output that it does since it never hits atoi.
 
I am sorry it was a misprint. Atoi is before return O
Code:
r=atoi(data);
return 0;


Martin
 
Obviously. Thank you xwb!!!!!
Code:
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
int main()
{
char *data;
int i,r;
data=malloc(11*sizeof(char));
for (i=0;i<10;i++)
data[i]='1';
data[10]='\0';
r=atoi(data);
free(data);
return 0;
}
This unfortunately proves how lame I am and how careful should I be while writing a code.

Martin
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top