Segmentation Fault (core dump) with Files (C- linux) - c

I'm getting a segmentation error (core dump) when I try to run this. It compiles perfectly but I get the error, and I don't know why. There must be a problem with a file writing because without this works good. Any help would be great. Thanks!
#include <stdio.h>
#include <time.h>
#include <unistd.h>
#include <crypt.h>
#include <string.h>
int
main(void)
{
FILE *f=fopen("shadow1.txt","w");
if (f=NULL)
{
printf("ERROR");
}
unsigned long seed[2];
char salt[] = "$1$........";
const char *const seedchars =
"./0123456789ABCDEFGHIJKLMNOPQRST"
"UVWXYZabcdefghijklmnopqrstuvwxyz";
char *password;
int i;
/* Generate a (not very) random seed.
You should do it better than this... */
seed[0] = time(NULL);
seed[1] = getpid() ^ (seed[0] >> 14 & 0x30000);
/* Turn it into printable characters from ‘seedchars’. */
for (i = 0; i < 8; i++)
salt[3+i] = seedchars[(seed[i/5] >> (i%5)*6) & 0x3f];
/* Read in the user’s password and encrypt it. */
password = crypt(getpass("Password:"), salt);
/* Print the results. */
//fprintf(f,"%s $ %s",password);
printf("Success Registration to file !");
fclose(f);
return 0;
}

if (f=NULL)
{
printf("ERROR");
}
was the problem...

void Register(char u,char p) {
you probably want these to be char * because of the fprintf that treats them as strings:
fprintf(f,"%s $ %s",u,p);
and since you pass char *s in:
char *password,*username;
//...
Register(username,password);
This would most likely have been caught by compiler warnings. It is a lot faster to get your answer from the compiler than from here.
If you can't figure out why your program isn't working, you can enable all the warnings you should need with -Wall -Wextra and turn warnings into errors with -Werror.

You are not allocating space to hold username so it will segfault on the scanf.

Related

undeclared function RegGetValue MinGW C compiler

I am trying to compile a C program using MinGW on Windows 7 (64-bit). The code is given below:
#include <windows.h>
#include <stdio.h>
#include <stdlib.h>
#include <stdint.h>
#include <string.h>
#include <inttypes.h>
void readRegDwordValue() {
HKEY hKey = HKEY_LOCAL_MACHINE;
char const *subKey = "Software\\Metpl\\My Program";
char const *pValue = "MJP_XXX";
uint32_t flags = RRF_RT_REG_DWORD;
int *pvData = NULL;
int64_t result = RegGetValue(hKey, &subKey, pValue, flags, NULL, pvData, sizeof(DWORD));
if (result != ERROR_SUCCESS) {
printf("Error getting value. Code: ");
printf("%" PRId64 "\n", result);
} else {
printf("Value data: ");
printf("%" PRId32 "\n", *(int32_t*)pvData);
}
}
int main() {
readRegDwordValue();
return 0;
}
I get the following warning:
gcc -O3 -Wall -c -o readReg.o readReg.c
readReg.c: In function 'readRegDwordValue':
readReg.c:13:22: warning: implicit declaration of function 'RegGetValue'; did you mean 'RegSetValue'? [-Wimplicit-function-declaration]
13 | int64_t result = RegGetValue(hKey, &subKey, pValue, flags, NULL, pvData, sizeof(DWORD));
| ^~~~~~~~~~~
| RegSetValue
I have included windows.h which includes winreg.h that contains the definition of the RegGetvalue function. Why is the compiler not able to find it? Also, since it is suggesting that I meant RegSetValue, does it mean it is able to find this one? !!
The linker gives the following error:
gcc readReg.o -o readReg.exe -L -liphlpapi -ladvapi32
d:/__sdk/mingw/bin/../lib/gcc/mingw32/9.2.0/../../../../mingw32/bin/ld.exe: readReg.o:readReg.c:(.text+0x45):
undefined reference to `RegGetValue'
collect2.exe: error: ld returned 1 exit status
What am I missing here? I have been pulling my hair over this for over 8 hours now and not able to understand where I am making the mistake. I have not been able to find much relevant discussion online on this either.
Desperately request some input on this so that I can move forward. Thanks in advance.
Finally! All the hair-pulling bore fruit. And, all the peripheral learning along the journey now seems exhilarating. Following is what works with MinGW-w64 (32-bit):
#include <windows.h>
#include <stdio.h>
#include <stdlib.h>
#include <stdint.h>
#include <string.h>
#include <inttypes.h>
char buffer[1024]; // Based on need. This is the max that I need.
DWORD bufferSize = sizeof(buffer);
DWORD readRegDwordValue(HKEY hKey, char const *subKey, char const *pValue) {
long unsigned int *p = NULL;
int64_t result = RegGetValue(hKey, subKey, pValue, RRF_RT_REG_DWORD, p, &buffer, &bufferSize);
if (result != ERROR_SUCCESS) {
return 4294967295; // max unsigned int.
}
return ((DWORD *)buffer)[0]; // return the first element of the buffer.
}
char * readStringValue(HKEY hKey, char const *subKey, char const *pValue) {
long unsigned int *p = NULL;
int64_t result = RegGetValue(hKey, subKey, pValue, RRF_RT_REG_SZ, p, &buffer, &bufferSize);
if (result != ERROR_SUCCESS) {
return "Error";
}
return (char *)buffer;
}
int main() {
char *string = readStringValue(HKEY_LOCAL_MACHINE, "Software\\Metpl\\My Program", "companyName");
printf("string:%s%s%d%s \n", string, " (length = ", strlen(string), ")");
DWORD integerValue = readRegDwordValue(HKEY_LOCAL_MACHINE, "Software\\Metpl\\My Program", "sampleInteger");
printf("integer:(%lu%s\n", integerValue, ")");
return 0;
}
I have tested this code and it gives correct results. Since I only need to get the correct result or an error, I have not added additional error-checking in the code.
Thanks, #CGio3, for pointing me to MinGW-w64. I have made many Portable C programs and a few Windows programs with the version I have and got too comfortable with it, I guess. Anyway, lesson learnt.
Hope this helps someone who has been struggling with the subject.

Managed variable usage in CUDA

I am trying to use managed variable in a CUDA program and I am getting a segmentation fault when trying to set the managed variable on the host side. I am doing exactly the same as mentioned in the documentation here(http://docs.nvidia.com/cuda/cuda-c-programming-guide/#managed-qualifier). Why is this happening?
#include <cuda.h>
#define THREADS_PER_BLOCK 32
#define BLOCKS_PER_SM 1
#define MB(x) ((x) << 20)
__device__ __managed__ int val = 0;
__global__ void test_kernel(char *src)
{
src[0] = val;
}
int main(int argc, char *argv[])
{
char *data;
int size = 2; // 2 MB
val = 100; //<--- seg fault gone if I comment this line
cudaMallocManaged(&data, MB(size));
test_kernel<<<BLOCKS_PER_SM, THREADS_PER_BLOCK>>>(data);
cudaDeviceSynchronize();
cudaFree(data);
return 0;
}
Sorry for the noise guys. It was a big FAIL on my part. My device is a 3.0 capability device, but I was compiling for compute_50 which is not supported. Thanks for the suggestions!

Segmentation Fault using SQLite3 with C

I'm trying to make a C program work and I'm getting mad. This is my code simplified to find the error:
#include <stdio.h>
#include <unistd.h>
#include <sqlite3.h>
int main(){
sqlite3 *conn;
sqlite3_stmt *res;
const char *tail, *sqlresult;
sqlite3_open("cubecat", &conn);
char buffer,query;
int id;
id= 1;
buffer = 'a';
if(buffer == 'a') snprintf(&query,100,"SELECT start FROM payloads WHERE id=%d", id);
printf("%s",&query);
int error = sqlite3_prepare_v2(conn, &query, 100, &res, &tail);
printf("%d",error);
}
The error is exactly on "sqlite_prepare_v2" function, because if I comment that line, there's no Segmentation Fault.
Thank you in advance!
char query;
snprintf(&query,100,"SELECT start FROM payloads WHERE id=%d", id);
This is what's wrong. query only reserves memory for one character. There's a reason the 2nd argument of snprintf() specifies the size. This code should be modified like this:
char query[100];
snprintf(query, sizeof(query), "SELECT start FROM payloads WHERE id=%d", id);

KERN_INVALID_ADDRESS has me stumped

I keep getting this error trying to run the debugger:
Program received signal EXC_BAD_ACCESS, Could not access memory.
Reason: KERN_INVALID_ADDRESS at address: 0x0000000000000000
0x00007fff8c2414f0 in strlen ()
Here is my code:
#include <stdio.h>
#include <cs50.h>
#include <string.h>
#include <ctype.h>
#include <stdlib.h>
int main(int argc, char *argv[])
{
char s2[25];
strcpy(s2, argv[1]);
int keyLen = strlen(s2);
printf("Please enter a string of text to be encrypted!\n");
string p = GetString();
for (int i = 0, n = strlen(p); i < n; i++)
{
if (isupper(p[i])){
int sum = (p[i] - 'A') + (s2[i % keyLen] - 'A');
char c = 'A' + sum%26;
printf("%c", c);
}
}
printf("\n");
printf("%d\n", keyLen);
}
I can compile the code with no errors and it works like it should. I am running the debugger to step into the for loop and look at what the math is doing to better understand it.
If GetString() returns null, then calling strlen(null) will give this error. Other errors on the part of GetString() could be causing this as well.
What is type 'string' in C?
Strlen() expects C-type array and not some custom 'string' type.
(+ there is a possibility of null input as pointed above)
I finally got it thanks to hmjd I was running it incorrectly I would start the program
gdb vignere HHHHH
Which is incorrect I ran it
gdb vignere
run HHHHHH
and it worked perfect!

Prevent segmentation fault in buffer overflow demonstration in Ubuntu 12

I am trying to run this piece of vulnerable C code:
#include <stdio.h>
#include <stdlib.h>
int add(int x, int y)
{
int z =10;
z = x + y;
return z;
}
main(int argc, char **argv)
{
int a = atoi(argv[1]);
int b = atoi(argv[2]);
int c;
char buffer[100];
gets(buffer);
puts(buffer);
c = add(a,b);
printf("Sum of %d+%d = %d\n",a, b, c);
exit(0);
}
I am trying to get past the segmentation fault so that I can input the integers but the segmentation fault prevents that. In the terminal I have tried:
gcc -ggdb -fno-stack-protector -U_FORTIFY_SOURCE -Wa,--execstack -o SimpleDemo SimpleDemo.c
I still get a segmentation fault. I am lost as to what to try next. As you can probably tell, I am an ubuntu newb. The bash code I am using comes from here:
http://www.evanjones.ca/buffer-overflow-101.html
I have been at this for while so would really appreciate some help
Cheers
Just explaining what hmjd is asking you to do.
Run (binary) 10 20

Resources