I copied some code that simply reads a file to a string and prints the string from an older program. It was working fine, so I decided to modify it a bit. The new program is
#include <stdio.h>
#include <string.h>
int main() {
FILE *itemlist = fopen("itemlist", "r");
char *currentstring, charbuffer[2];
// char itemstart = 0;
while (fgets(charbuffer, 2, itemlist)) {
strcat(currentstring, charbuffer);
}
printf("%s", currentstring);
return 0;
}
And it works as expected. But when I uncomment the itemstart line, it gives a segmentation fault. I'm not even using it and as far as I'm concerned, initializing an char to 0 is not illegal. I thought it was an issue with types, then I changed it to a short and then to int and it was still giving a segfault.
But then I removed the = 0 part and it worked again. Then I decided to put it back, debug the binary with gdb, and the segfault was at strcat.
How is this possible?
currentstring is a dangling pointer, so strcat(currentstring, charbuffer); results in undefined behavior.
Probably uncommenting char itemstart = 0 initializes some memory to 0 and the access violation is made visible, however this is just a guess. Undefined behavior means anything can happen.
You should allocate memory for currentstring:
currentstring = malloc(10); //or whatever length you need
You need to allocate some space for currentstring.
Segfaults when uncommenting unrelated lines are made possible by the unsafeness of the C language. The end behavior of an incorrect program is determined by subtle choices made by the compiler.
When confronted to such madness, you should try to correct your code first. This is of course, not always easy. On a 8 lines program, you should be ok though.
You must allocate space for currentstring variable and control the size of it for avoid segment fault/heap corruption.
#define MAX_BUFFER_SIZE 32
//...
FILE *itemlist = fopen("itemlist", "r");
char *currentstring = malloc(MAX_BUFFER_SIZE+1);
char *tmpbuf;
char charbuffer[2];
// char itemstart = 0;
int bytesloaded = 0;
while (fgets(charbuffer, 2, itemlist)) {
if(bytesloaded + 2 > buf_size) {
/* call realloc() */
buf_size += MAX_BUFFER_SIZE;
tmpbuf = realloc(currentstring, buf_size);
if(tmpbuf == NULL) { /* Get off loop. Using break or return. */
break;
}
currentstrig = tmpbuf;
}
memcpy(currentstring + bytesloaded, charbuffer, 2);
bytesloaded += 2;
}
//...
free(currentstring);
I haven't tested,but I believe that it works.
Related
Hi I wrote this code and it worked but in the end, "the program has stopped working"
#include <stdio.h>
#include <malloc.h>
#include <stdlib.h>
#include <string.h>
void main()
{
char *s;
s=(char*)malloc(sizeof(char));
printf("Enter a string:\n");
gets(s);
while (*s)
{
if (*s>= 65 && *s<=90)
printf("%c",*s+32);
else if(*s>=97 && *s<=122)
printf("%c",*s-32);
else
printf("%c",*s);
*s++;
}
free(s);
}
That code does not work, in fact it has undefined behavior.
This:
s = (char *) malloc(sizeof(char));
allocates 1 byte of storage, into which you then scan a string, thus very likely leading to buffer overflow. The buffer can only hold a single string, i.e. string of 0 characters before the terminator character at the end.
You meant:
s = malloc(128);
or something like that.
There's no need to cast, and sizeof (char) is always 1 so that doesn't add anything.
Also, as more of a code review, magic numbers in code is generally considered a bad idea, instead write:
if (*s >= 'A' && *s <= 'Z')
or even better
if (isupper((unsigned int) *s))
to not hard-code a depdency on ASCII.
UPDATE Oh, and as pointed out in a comment, you can't change the value of s and then pass the changed value to free(), that is undefined behavior also. The address passed to free() must be the same as the one you got back from malloc().
Use a separate variable for the iteration:
char *p = s;
and only free() the original s.
Firstly, by s=(char*)malloc(sizeof(char)); you are allocating only 1 byte of memory for buffer. Allocate enough memory to store the input. Also avoid typecasting malloc() result. Better version looks like
s = malloc(MAX * sizeof(*s));/* MAX is num of bytes you need to define */
Secondly don't use gets() use fgets() instead. Read man 3 gets or check https://linux.die.net/man/3/gets
Finally use int main(void) { } instead of just main(){ }
And more importately when you do free(s) at that time s doesn't point to memory which was earlier allocated to it because of s++ so it may result error like
free(): invalid pointer:
So don't change s use s[row] while iterating OR you can assign s to other pointer and then you can do free(s).
Complete code
int main() {
char *s = NULL;
int size = MAX*sizeof(*s);/*define MAX value, it is no of bytes need*/
s = malloc(size);/* this is generic
sizeof(*s) works for any data type */
printf("Enter a string:\n");
fgets(s,size,stdin);/* use fgets() instead of gets() */
int row = 0;
while (s[row]!='\0') {
if ( *(s+row) >= 65 && *(s+row) <= 90)
printf("%c",*(s+row) + 32);
else if( *(s+row) >=97 && *(s+row) <= 122)
printf("%c",*(s+row) - 32);
else
printf("%c",*(s+row));
row++;
}
free(s);/* s still points to same location */
return 0;
}
Also you can use isupper() instead of comparing each char ASCII value.
This is wrong.
s = (char*)malloc(sizeof(char));
printf("Enter a string:\n");
gets(s);
s = (char*)malloc(sizeof(char)); allocates 1 byte of memory. And then with
gets(s); you get a string, which will be Undefined Behavior.
You have to changed it to
s = malloc(MAX_LENGTH * sizeof(char)); //MAX_LENGTH is user defined
Additionally, you must check if malloc() returned anything. If it returns NULL then it means no memory is allocated and all of the existing program will invoke undefined behavior.
Also, there is no need to cast the malloc result, so to further improve your code, you need to change it to,
s = malloc(MAX_LENGTH * sizeof(char));
if(s == NULL)
{
// Add error handling here
}
Also,
void main()
isn't by the standard anymore, see This post which explains why. If you want to know what C11 standard states about it, then refer the standard here: Section 5.1.2.2.1 Program startup
So change it to,
int main(void)
You should make sure that you call free(s); only if it was allocated. As one of the comments below rightly indicates that free(NULL); is NOT a problem, but it also have no effect, so why call it anyway.
Make s point to NULL again, but its irrelevant in this piece of code.
I'm encoding the contents of a message struct into a buffer.
int encode(const struct message *msg, unsigned char *buffer, size_t max_size)
{
if (buffer == NULL)
return -1;
unsigned char *buf_pos = buffer;
unsigned char *ep = buffer + max_size;
if (buf_pos + 1 <= ep) {
*buf_pos++ = SYNC_WORD_1;
} else {
return buf_pos - buffer;
}
.
.
.
}
When I call encode(&message, "", 1024); I encounter a segmentation fault as expected. My understanding is that the segfault is caused by an attempt to access memory not allocated to the program, since "" will contain just the null terminator and I'm passing it in place of a pointer.
The problem I'm having is when I try to handle this error. I haven't found a way to identify the invalid input that doesn't either cause a false-positive with valid inputs or another segfault.
So what's the correct way to weed out this kind of input?
This cannot be done.
You're basically asking "given a pointer, how can I ensure that there are n byets of writable space there?" which is a question C doesn't help you with.
This is, at its root, because pointers are just addresses, there is no additional meta information of the kind you're after associated with each pointer value.
You can check the pointer for being NULL, but that's basically the only pointer value you can be certain is invalid. Non-portably (on embedded targets especially) you can get clever and check if the pointer is in various known non-writable regions, but that's still very coarse.
I guess you are not checking the size of the buffer when you copy it in buf_pos
When trying to access buf_pos + 1, you may going into some memory you don't have acces to, causing a segmentation fault.
Did you try usung valgrind on your executable ?
When asking a question about a runtime problem, as this question is doing, post the actual input, the expected output, the actual output and most importantly, post code code that cleanly compiles, is short, and still exhibits the problem.
The following code will handle a pointer to a string that only contains a NUL byte.
However, that is not the only problem. What if the passed in buffer pointer may be pointing to a char array in read only memory, then the posted code would still result in a seg fault event.
int encode(const struct message *msg, unsigned char *buffer, size_t max_size)
{
if (buffer == NULL)
return -1;
if( strlen(buffer) == 0 )
return -1;
unsigned char *buf_pos = buffer;
unsigned char *ep = buffer + max_size;
if (buf_pos + 1 <= ep)
{
*buf_pos++ = SYNC_WORD_1;
}
else
{
return buf_pos - buffer;
}
.
.
.
}
To be able to help you more, you need to post the scenarios under which this function will be called.
I want to store a single char into a char array pointer and that action is in a while loop, adding in a new char every time. I strictly want to be into a variable and not printed because I am going to compare the text. Here's my code:
#include <stdio.h>
#include <string.h>
int main()
{
char c;
char *string;
while((c=getchar())!= EOF) //gets the next char in stdin and checks if stdin is not EOF.
{
char temp[2]; // I was trying to convert c, a char to temp, a const char so that I can use strcat to concernate them to string but printf returns nothing.
temp[0]=c; //assigns temp
temp[1]='\0'; //null end point
strcat(string,temp); //concernates the strings
}
printf(string); //prints out the string.
return 0;
}
I am using GCC on Debain (POSIX/UNIX operating system) and want to have windows compatability.
EDIT:
I notice some communication errors with what I actually intend to do so I will explain: I want to create a system where I can input a unlimited amount of characters and have the that input be store in a variable and read back from a variable to me, and to get around using realloc and malloc I made it so it would get the next available char until EOF. Keep in mind that I am a beginner to C (though most of you have probably guess it first) and haven't had a lot of experience memory management.
If you want unlimited amount of character input, you'll need to actively manage the size of your buffer. Which is not as hard as it sounds.
first use malloc to allocate, say, 1000 bytes.
read until this runs out.
use realloc to allocate 2000
read until this runs out.
like this:
int main(){
int buf_size=1000;
char* buf=malloc(buf_size);
char c;
int n=0;
while((c=getchar())!= EOF)
buf[n++] = c;
if(n=>buf_size-1)
{
buf_size+=1000;
buf=realloc(buf, buf_size);
}
}
buf[n] = '\0'; //add trailing 0 at the end, to make it a proper string
//do stuff with buf;
free(buf);
return 0;
}
You won't get around using malloc-oids if you want unlimited input.
You have undefined behavior.
You never set string to point anywhere, so you can't dereference that pointer.
You need something like:
char buf[1024] = "", *string = buf;
that initializes string to point to valid memory where you can write, and also sets that memory to an empty string so you can use strcat().
Note that looping strcat() like this is very inefficient, since it needs to find the end of the destination string on each call. It's better to just use pointers.
char *string;
You've declared an uninitialised variable with this statement. With some compilers, in debug this may be initialised to 0. In other compilers and a release build, you have no idea what this is pointing to in memory. You may find that when you build and run in release, your program will crash, but appears to be ok in debug. The actual behaviour is undefined.
You need to either create a variable on the stack by doing something like this
char string[100]; // assuming you're not going to receive more than 99 characters (100 including the NULL terminator)
Or, on the heap: -
char string* = (char*)malloc(100);
In which case you'll need to free the character array when you're finished with it.
Assuming you don't know how many characters the user will type, I suggest you keep track in your loop, to ensure you don't try to concatenate beyond the memory you've allocated.
Alternatively, you could limit the number of characters that a user may enter.
const int MAX_CHARS = 100;
char string[MAX_CHARS + 1]; // +1 for Null terminator
int numChars = 0;
while(numChars < MAX_CHARS) && (c=getchar())!= EOF)
{
...
++numChars;
}
As I wrote in comments, you cannot avoid malloc() / calloc() and probably realloc() for a problem such as you have described, where your program does not know until run time how much memory it will need, and must not have any predetermined limit. In addition to the memory management issues on which most of the discussion and answers have focused, however, your code has some additional issues, including:
getchar() returns type int, and to correctly handle all possible inputs you must not convert that int to char before testing against EOF. In fact, for maximum portability you need to take considerable care in converting to char, for if default char is signed, or if its representation has certain other allowed (but rare) properties, then the value returned by getchar() may exceed its maximum value, in which case direct conversion exhibits undefined behavior. (In truth, though, this issue is often ignored, usually to no ill effect in practice.)
Never pass a user-provided string to printf() as the format string. It will not do what you want for some inputs, and it can be exploited as a security vulnerability. If you want to just print a string verbatim then fputs(string, stdout) is a better choice, but you can also safely do printf("%s", string).
Here's a way to approach your problem that addresses all of these issues:
#include <stdio.h>
#include <string.h>
#include <limits.h>
#define INITIAL_BUFFER_SIZE 1024
int main()
{
char *string = malloc(INITIAL_BUFFER_SIZE);
size_t cap = INITIAL_BUFFER_SIZE;
size_t next = 0;
int c;
if (!string) {
// allocation error
return 1;
}
while ((c = getchar()) != EOF) {
if (next + 1 >= cap) {
/* insufficient space for another character plus a terminator */
cap *= 2;
string = realloc(string, cap);
if (!string) {
/* memory reallocation failure */
/* memory was leaked, but it's ok because we're about to exit */
return 1;
}
}
#if (CHAR_MAX != UCHAR_MAX)
/* char is signed; ensure defined behavior for the upcoming conversion */
if (c > CHAR_MAX) {
c -= UCHAR_MAX;
#if ((CHAR_MAX != (UCHAR_MAX >> 1)) || (CHAR_MAX == (-1 * CHAR_MIN)))
/* char's representation has more padding bits than unsigned
char's, or it is represented as sign/magnitude or ones' complement */
if (c < CHAR_MIN) {
/* not representable as a char */
return 1;
}
#endif
}
#endif
string[next++] = (char) c;
}
string[next] = '\0';
fputs(string, stdout);
return 0;
}
I have encountered so called cryptic realloc invalid next size error , I am using gcc on linux my code is
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
int main()
{
int i;
char *buf;
char loc[120];
buf = malloc(1);
int size;
for(i=0;i<1920;i++)
{
sprintf(loc,"{Fill_next_token = my_next_token%d; Fill_next_token_id = my_next_token_id = my_next_token_id%d}",i,i);
size = strlen(buf)+strlen(loc);
printf("----%d\n",size);
if(!realloc(buf,size))
exit(1);
strcat(buf,loc);
}
}
(mine might be duplicate question) here the solution somewhere lies by avoiding strcat and to use memcpy , But in my case I really want to concatenate the string . Above code works for good for such 920 iterations but in case 1920 realloc gives invalid new size error. Please help to find alternative of concatenating , looking forward to be a helpful question for lazy programmers like me .
Your code has several issues:
You are not accounting for null terminator when deciding on the new length - it should be size = strlen(buf)+strlen(loc)+1;
You are ignoring the result of realloc - you need to check it for zero, and then assign it back to buf
You do not initialize buf to an empty string - this would make the first call of strlen produce undefined behavior (i.e. you need to add *buf = '\0';)
Once you fix these mistakes, your code should run correctly:
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
int main() {
int i;
char *buf= malloc(1);
*buf='\0';
char loc[120];
for(i=0;i<1920;i++) {
sprintf(loc,"{Fill_next_token = my_next_token%d; Fill_next_token_id = my_next_token_id = my_next_token_id%d}",i,i);
int size = strlen(buf)+strlen(loc)+1;
printf("----%d\n",size);
char *tmp = realloc(buf,size);
if(!tmp) exit(1);
buf = tmp;
strcat(buf, loc);
}
}
Demo.
buf is not a valid string so strcat() will fail since it expects a \0 terminated string.
If you want to realloc() buf then you should assign the return value of realloc() to buf which you are not doing.
char *temp = realloc(buf,size+1);
if(temp != NULL)
buf = temp;
Point 1. Always use the return value of realloc() to access the newly allocated memory.
Point 2. strcat() needs a null-terminating string. Check the first iteration case.
Alright guys, this is my first post here. The most recent assignment in my compsci class has us coding a couple of functions to encode and decode strings based on a simple offset. So far in my encryption function I am trying to convert uppercase alphas in a string to their ASCII equivalent(an int), add the offset(and adjust if the ASCII value goes past 'Z'), cast that int back to a char(the new encrypted char) and put it into a new string. What I have here compiles fine, but it gives a Segmentation Fault (core dumped) error when I run it and input simple uppercase strings. Where am I going wrong here? (NOTE: there are some commented out bits from an attempt at solving the situation that created some odd errors in main)
#include <stdio.h>
#include <string.h>
#include <ctype.h>
//#include <stdlib.h>
char *encrypt(char *str, int offset){
int counter;
char medianstr[strlen(str)];
char *returnstr;// = malloc(sizeof(char) * strlen(str));
for(counter = 0; counter < strlen(str); counter++){
if(isalpha(str[counter]) && isupper(str[counter])){//If the character at current index is an alpha and uppercase
int charASCII = (int)str[counter];//Get ASCII value of character
int newASCII;
if(charASCII+offset <= 90 ){//If the offset won't put it outside of the uppercase range
newASCII = charASCII + offset;//Just add the offset for the new value
medianstr[counter] = (char)newASCII;
}else{
newASCII = 64 + ((charASCII + offset) - 90);//If the offset will put it outside the uppercase range, add the remaining starting at 64(right before A)
medianstr[counter] = (char)newASCII;
}
}
}
strcpy(returnstr, medianstr);
return returnstr;
}
/*
char *decrypt(char *str, int offset){
}
*/
int main(){
char *inputstr;
printf("Please enter the string to be encrypted:");
scanf("%s", inputstr);
char *encryptedstr;
encryptedstr = encrypt(inputstr, 5);
printf("%s", encryptedstr);
//free(encryptedstr);
return 0;
}
You use a bunch of pointers, but never allocate any memory to them. That will lead to segment faults.
Actually the strange thing is it seems you know you need to do this as you have the code in place, but you commented it out:
char *returnstr;// = malloc(sizeof(char) * strlen(str));
When you use a pointer you need to "point" it to allocated memory, it can either point to dynamic memory that you request via malloc() or static memory (such as an array that you declared); when you're done with dynamic memory you need to free() it, but again you seem to know this as you commented out a call to free.
Just a malloc() to inputstr and one for returnstr will be enough to get this working.
Without going any further the segmentation fault comes from your use of scanf().
Segmentation fault occurs at scanf() because it tries to write to *inputstr(a block of location inputstr is pointing at); it isn't allocated at this point.
To invoke scanf() you need to feed in a pointer in whose memory address it points to is allocated first.
Naturally, to fix the segmentation fault you want to well, allocate the memory to your char *inputstr.
To dynamically allocate memory of 128 bytes(i.e., the pointer will point to heap):
char *inputstr = (char *) malloc(128);
Or to statically allocate memory of 128 bytes(i.e., the pointer will point to stack):
char inputstr[128];
There is a lot of complexity in the encrypt() function that isn't really necessary. Note that computing the length of the string on each iteration of the loop is a costly process in general. I noted in a comment:
What's with the 90 and 64? Why not use 'A' and 'Z'? And you've commented out the memory allocation for returnstr, so you're copying via an uninitialized pointer and then returning that? Not a recipe for happiness!
The other answers have also pointed out (accurately) that you've not initialized your pointer in main(), so you don't get a chance to dump core in encrypt() because you've already dumped core in main().
#include <ctype.h>
#include <stdlib.h>
#include <string.h>
char *encrypt(char *str, int offset)
{
int len = strlen(str) + 1;
char *returnstr = malloc(len);
if (returnstr == 0)
return 0;
for (int i = 0; i < len; i++)
{
char c = str[i];
if (isupper((unsigned char)c))
{
c += offset;
if (c > 'Z')
c = 'A' + (c - 'Z') - 1;
}
returnstr[i] = c;
}
return returnstr;
}
Long variable names are not always helpful; they make the code harder to read. Note that any character for which isupper() is true also satisfies isalpha(). The cast on the argument to isupper() prevents problems when the char type is signed and you have data where the unsigned char value is in the range 0x80..0xFF (the high bit is set). With the cast, the code will work correctly; without, you can get into trouble.