List of "Always wrong" snippets in C [closed] - c

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 6 years ago.
Improve this question
Was talking to a colleague today on one-spot errors - I.e. errors (or at least patterns that should ring an alarm bell) in code that a decent programmer should be able to spot at a single glance like
x = malloc (strlen(y));
while (!feof (f)) {
...
}
char *f(){
char x[100];
...
return x;
}
Who has similar snippets of such patterns? I would suggest anyone who has been on SO for a while will have his personal favourites of those

char *buf;
scanf("%s", buf);
This is wrong, because no memory has been allocated for buf.
char buf[100];
scanf("%s", &buf);
This is wrong, because scanf expects a char *, not a char (*)[n].
char c;
while ((c = getchar()) != EOF)
putchar(c);
This is wrong, because EOF does not fit in the range of a char. Use int instead.
fflush(stdin);
fflush is undefined for input streams, like stdin, albeit this is implemented as an extension in some compilers, like Microsoft C.
#define IN 0;
Do not put semicolons at the end of a #define.
blk = realloc(blk, n);
If realloc fails, any contents in blk will be lost, because realloc will return NULL. To solve the problem, copy the return value into a temporary and only if the temporary is not NULL, copy to the final destination.

Related

pointer and char array [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 4 years ago.
Improve this question
I am using gcc 4.9.2-10 deb8u1 compiler to compile
Here is my code
#include <stdio.h>
int main(){
char *s;
char sa[10] , sb[10];
scanf("%s", sa);
printf("line\n");
scanf("%s", sb);
printf("%s %s", sa, sb);
}
Above code is no any problem if char is under the space provided
However
scanf("%s", s);
printf("line\n");
scanf("%s", sa);
printf("%s %s", s, sa);
Input:
$:
Hu
Result:
line
(null) Hu
Someone could told me what happen about second code wrong .?
I cannot figure out why i cannt input second one .. Thx a lot .!
In you code
char *s;
char sa[10] , sb[10];
you can't do much with s.
scanf("%s", sa);
is ok, provided the input fits. You can jump through a few hoops, reading the inputs in chunks in a loop if it might be longer (see here)
However, in you "However" section of the question you try
scanf("%s", s);
Since s doesn't point to memory - you'd need to have allocated some - you have undefined behaviour, so anything could happen.
I cannot figure out why i cannt input second one ? because s is not initialize and not having any valid address & doing scanf() on that results in undefined behaviour.
First allocate the memory and then scan the user input.
int main() {
char *s; /* its un initialized */
s = malloc(size); /* this you need to do ? specify the size value */
fgets(s,size,stdin);/* its advisable as its not having overflow problem */
printf("%s\n",s);
/* once job is done , free it by calling free(s) */
free(s);
return 0;
}
Use fgets() instead of scanf() to scan the user input for the reason listed in comments.

Unhandled exception thrown: read access violation [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 7 years ago.
Improve this question
I was doing an assignment for my C class in school and I hit a little snag.
#include <stdio.h>
char stringToUpper(char * sName )
{
while(*sName != '\0')
{
stringToUpper (* sName);
++* sName;
}
}
int main()
{
char str[50];
char * sName;
printf("Please enter your name ");
scanf("%s", str);
printf("Hello %s ", str);
sName = str;
stringToUpper(sName);
printf("Name in uppercase: %s ", sName);
}
I tried looking for other solutions already, however I found that everyone else's problems were much more advanced than the level I'm at and really just couldn't follow it. I've still a little new at working with pointers and still a little confused about how they work (only a few weeks into the class) so I feel like the issue has something to do with that. I'm almost certain that the issue has something to do with the while statement.
This is the error I get:
Unhandled exception thrown: read access violation.
sName was 0x41.
If there is a handler for this exception, the program may be safely continued.
Thanks in advanced for whatever help I receive.
Your stringToUpper function has some issues:
while(*sName != '\0')
{
stringToUpper (* sName);
++* sName;
}
You could be calling toupper to change to upper case and assigning the value back to *sName instead of having the function call itself. In fact, the call you had is incorrect because you're passing a char to a function expecting a char *. In the next iteration of stringToUpper, it attempts to dereference that invalid pointer which causes the crash.
You should be incrementing sName (which points to the current character), not *sName.
The corrected version:
while(*sName != '\0')
{
*sName=toupper(*sName);
++sName;
}

Parse int and char into two separate values [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
I'm having the issues of trying to separate 1s or 2d into int 1 and char 's' and then storing them as separate values. How would I go about doing this. I know I can't do it with strtok since there are no delimiters.
Use strtol. For example,
char *endptr;
val = strtol(input_str, &endptr, 10;
next_char = *endptr;
As discussed in the manpage, http://man7.org/linux/man-pages/man3/strtol.3.html, the second parameter is a pointer to a char pointer and after the conversion, the char pointer points to the following character.
You can access each char from the string by index. To convert char to int (not by ascii value, '1' to 1) you just do the following:
int a = c[0]-'0';
and for the char:
char b = c[1];

How can I read and process this kind of file [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Closed 8 years ago.
This question appears to be off-topic because it lacks sufficient information to diagnose the problem. Describe your problem in more detail or include a minimal example in the question itself.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Improve this question
I 12 0
I 9 1
I 26 0
I 25 2
B 26
P 0
R 25
A
So, what I need to do is read a file containing these characters/numbers and whenever I encounter a letter, I call a function to process whatever comes after the letter (aka the numbers).
For example:
When reading "I" I have to call the function to INSERT a certain number in a certain level of a Skip List; or when reading B, I need to search for a specific number in the Skip List, etc.
Problem is I'm really bad at reading from a file, can you guys enlighten me?
You can do this with file operations in c,
i am just giving you hints,
FILE *pFilePtr; // file pointer(handle of file)
pFilePtr = fopen(argv[1],"r");
//define buffer to store data read line by line data
char buf[32]={0};
//Now you can run a while loop to read entire file
with fread() to get whole first line(until '\n')
while(!feof(pFilePtr))
{
if(NULL != fgets(buf,32,pFilePtr))
// perform string operation on buffer to extract letters and digits
// and according to that call functions you need
}
#include <stdio.h>
#include <string.h>
int main(void) {
FILE *fptr;
char mystring[20];
int number;
fptr = fopen("Input.txt", "r");
while(fscanf(fptr , "%s %d", mystring, &number) != EOF) {
printf("%s %d\n", mystring, number);
if(strcmp(mystring, "I") == 0) {
printf("Implement the reqd function here\n");
}
}
}

Line by line reading, seg fault [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 8 years ago.
Improve this question
this code gives an instant seg fault,I tried placing printf's all over, I even tried to printf something just after the int=0; line but no matter what I did, it does not print anything but a segmentation fault. The file exists, also its location is the same with where I do the execution.
The file includes city names, one name on each line, nothing else, how do I read them and store them in an array :/
what if there was a number after each city, would the reading still be the same?
NewYork 5
LosAngeles 12
California 7
and the code;
int i=0;
char **city_names = malloc(sizeof(char*));
FILE* fp;
fp = fopen("abc.txt","r");
while(!feof(fp)){
city_names[i] = realloc(city_names[i],sizeof(char)*255);
fscanf(fp,"%s",city_names[i]);
i++;
}
fclose(fp);
You are only allocating a single char * of memory in your malloc then accessing beyond it in the while loop.
If you are going to do a 2D malloc array, you need to malloc each pointer, then malloc assign a malloc into each to the max string size (yuck).
char **city_names = malloc(sizeof(char *) * kNumCities);
for(int i = 0; i &lt kNumCities; i++)
city_names[i] = malloc(sizeof(char) * kMaxStringSize);
Or do something like char city_name[3][256] instead to get it up and running.
I'd also like to add that this sort of reading is very unsafe. You are reading an unknown amount of bytes into a fixed buffer size. If the string you read in were more than 255 bytes, you will destroy memory. You'd be better off using an fread() into a fixed size buffer type solution (or ftell() then file and read it all in at once for best efficiency) and then do your reading off the buffer. Not to mention all the overhead of malloc and realloc (they do add up).
And the while(!feof(fp)) logic is wrong too; for an empty file it still tries to scanf something and increments i.
Never test for EOF before you read in C. Test after reading.
The idiomatic code to iterate over characters on stdin in C is
int c; /* NOT char. */
while ((c = getchar()) != EOF) {
/* do something with c */
}
To iterate over lines:
char line[MAXLINE];
while (fgets (line, sizeof line, stdin) != NULL) {
/* do something with line */
}
int i=0;
char **city_names = malloc(sizeof(char*));
FILE* fp;
fp = fopen("data.txt","r");
while(!feof(fp)){
city_names[i] = (char*)malloc(sizeof(char)*255);
if(1!=fscanf(fp,"%s %*d",city_names[i]))break;
++i;
city_names = (char**)realloc(city_names, (i+1)*sizeof(char*));
}
fclose(fp);

Resources