pereges <Br*****@gmail.comwrites:
i guess the problem arises because you have not allocated any memory
for the string. Probably you can try this because it seems to work for
me:
Seems to. You are lucky. I have listed some issues below. Hope it helps.
>
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
int main(void)
{
char *t[5]; /*= {"BASIC"};*/
int i;
i = strlen("BASIC");
t[0] = malloc(i * sizeof(char));
strcpy(t[0],"BASIC");
printf("....%s",t[0]);
return EXIT_SUCCESS;
}
Your code has errors. I thought Id try the output of "splint" to make
the diagnosis a little more consistent.
Since I didn't see the previous post I wonder why you are creating an
array of 5 character pointers? or did you think the 5 was the length of
BASIC? It's not clear in the absence of any comment what you really
intend.
From splint(*) :
test2.c:9:3: Assignment of size_t to int: i = strlen("BASIC")
In other words strlen returns a size_t and not an int. Personally when I
write C I tend to still use "int" where I KNOW the string is short
enough. But its not "correct". Use a size_t.
Also you only malloc enough for the "BASIC" part and not for the
trailing zero to indicate "end of string". Look up "strings" in C. Read
the manual for strlen and strcpy. This is one of the most basic but
important things to know in C.
More from splint:
test2.c:10:34: Parameter to sizeof is type char: sizeof(char)
Operand of sizeof operator is a type. (Safer to use expression, int *x =
sizeof (*x); instead of sizeof (int).) (Use -sizeoftype to inhibit warning)
Personally, for me, this line would just be
t[0] = malloc(strlen("BASIC")+1);
But even then we have a problem that something like splint can tell us
no matter how much we think we know best:
strcpy (t[0], ...)
A possibly null pointer is passed as a parameter corresponding to a formal
parameter with no /*@null@*/ annotation. If NULL may be used for this
parameter, add a /*@null@*/ annotation to the function parameter declaration.
Why is this? It's because you did not check for malloc returning NULL,
but that is another story and down to good programming practices.
So following that hint we can do:
char *p = malloc(strlen("BASIC")+1);
if(p==NULL)
return EXIT_FAILURE;
t[0]=p;
strcpy(t[0],"BASIC");
(*)(Splint is a tool for statically checking C programs for
security vulnerabilities and coding mistakes. With minimal effort,
Splint can be used as a better lint. If additional effort is invested
adding annotations to programs, Splint can perform stronger checking
than can be done by any standard lint. See
http://www.splint.org/ ).