Program received signal from GDB: EXC_BAD_ACCESS - macos

Well, I'm starting development on the Mac OS X this code that you'll see is in a book that I bought, really basic like Chapter 3. And I can't run it. PLEASE HELP ME:
C301.m :
#import <Foundation/Foundation.h>
int main (int argc, const char * argv[]) {
if (argc == 1) {
NSLog (#"You need to provide a file name");
return -1;
}
FILE *wordFile = fopen("tmp/words.txt", "r");
char word[100];
while (fgets(word, 100, wordFile)) {
word[strlen(word) - 1] = '\0';
NSLog(#"%s is %d characters long", word, strlen(word));
}
fclose(wordFile);
return 0;
} //main
The file is in its place.
Thank you so much!

I am guessing wordFile is NULL (you should check for this); that you are mistaken: the file in fact does not exist, and finally that you really meant "/tmp/words.txt" instead of "tmp/words.txt"

Related

not able to read a text file in vs2010 using c .. i am new to vs please help me

i kept my text file at exactly same place where .exe is existing , then also its not working ..
hi this is my code , i kept my text file at exactly same place where .exe is existing , then also its not working ..
hi this is my code , i kept my text file at exactly same place where .exe is existing , then also its not working ..
int main(int argc, _TCHAR* argv[])
{
int result = 0;
char ca, file_name[25];
FILE *fp;
//printf("Enter the name of file you wish to see\n");
gets(file_name);
fp = fopen("sample.txt","r"); // read mode
if( fp == NULL )
{
perror("Error while opening the file.\n");
//exit(EXIT_FAILURE);
}
if( fgets (str, 60, fp)!=NULL )
{
/* writing content to stdout */
puts(str);
}
fclose(fp);
}
Try this , i basically work in C & C++ , i use this code to perform file operation
int main()
{
char filename[10];char extension[5]=".txt";
printf("Enter the name of file you wish to see\n");
gets(filename);
fflush(stdin);
filename[10]='\0';
strcat(filename,extension);
puts(filename);
FILE *p; char acline[80];
p=fopen(filename,"r");
if(p==NULL)
{
printf("%s file is missing\n",filename);system("pause");
}
fseek(p,0,SEEK_SET); // Setting file pointer to beginning of the file
while (!feof(p)) // Detecting end of file
{
fgets(acline,80,p);
puts(acline);
}
printf("\n File end\n");
system("pause");
}
*but while(!feof()) has certain issues see this

scanf,fgets, fgetc get skipped inside loop

Im trying to make a recursive menu.
This program will later work with a tree(hojanodo), thats why I keep track of the root.
Problem: For some reason the fgets/fgetc is being skipped inside the recursivity on the second run, why does this happen?
I want the user to input either 1,2 or 3.(int)
What would be the fix for this? and is this the best way to implement a menu?
Here's what I have right now:(It compiles and runs so you can test it out but doesn't really work like I would like to..)
#include<stdio.h>
#include<stdlib.h>
typedef struct node{
char ch;
int i;
struct node *left;
struct node *right;
}hojaNodo;
int handle_menu(int eventHandler, hojaNodo **root);
int opcion_menu();
char get_symbol();
int get_userMenuInput();
int intro();
int main(){
hojaNodo *treeRoot = NULL;
intro();
// system("clear");
handle_menu(opcion_menu(), &treeRoot);
return 0;
}
int opcion_menu(){
int userOption;
printf("1.Agrega un Simbolo.\n");
printf("2.Listar Codigo\n");
printf("3.Exit");
userOption = get_userMenuInput();
printf("User: %d",userOption);
if(userOption < 4 && userOption > 0){
return userOption;
}
else
return -1;
}//eof opcion_menu
int handle_menu(int userOption,hojaNodo **root){
hojaNodo *tempRoot = NULL;
tempRoot = *root;
int valor;
char simbol;
switch(userOption){
case 1:
simbol = get_symbol();
printf("Simbol: %c", simbol);
break;
case 2:
printf("List Nodes\n");
break;
case 3:
printf("Exit");
userOption = -1;
// destroy_tree(root);
break;
default:
printf("userOption Error, Bye!");
break;
}//eof switch
if(userOption != -1)
handle_menu(opcion_menu(),&tempRoot);
// return userOption;
return -1;
}//eof menu()
char get_symbol(){
/*char userKey[3]
fgets(userKey,len,stdin);*/
char simbolo;
printf("Give me a symbol.");
simbolo = fgetc(stdin);
return simbolo;
}
int get_userMenuInput(){
char userKey[3];
int userOption;
size_t len;
len = sizeof(userKey);
fgets(userKey,len,stdin);
userOption = atoi(userKey);
//printf("User Option: %d\n", userOption);
return userOption;
}
Well apart from all the comments related to recursion and other changes suggested, please check this out. fgets() function needs flushing the input stream. It can be done using fflush() or fgetc().
A simple solution would be:
In function:
int opcion_menu(){
...
fgets(userKey,2,stdin);
fgetc(stdin); // Add this statement
Also in function:
int handle_menu(int userOption,hojaNodo **root)
case 1:
printf("Give me a choice : ");
fgets(userKey,2,stdin);
fgetc(stdin); // add this statement
fgets reads in at most one less than size characters from stream and stores them into the buffer pointed to by string. This will lead the newline character still available in Input Stream which need to be flushed. If this newline character is not read from Input stream, than this would become the input for next fgets function and ultimately it will skip the fgets(since it has already got its input a newline character)
fgetc(stdin) will flush out these extra newline character.
I don't know if this might help anyone.
In my case, I had to 'free' the buffer from the char with this function:
void clean(){
char cTemp;
while((cTemp = getchar()) != '\n')
;
}
Im not really sure why this works but it does(if anyone does, please add it to my answer).
I call it right before I call get_userOption();

WinAPI C++ client detect write on anonymous pipe before reading

I am writing a C++ (Windows) client console application which reads from an anonymous pipe on STDIN. I would like to be able to use my program as follows:
echo input text here | my_app.exe
and do something in the app with the text that is piped in
OR
my_app.exe
and then use some default text inside of the app instead of the input from the pipe.
I currently have code that successfully reads from the pipe on STDIN given the first situation:
#include <Windows.h>
#include <iostream>
#include <string>
#define BUFSIZE 4096
int main(int argc, const char *argv[]) {
char char_buffer[BUFSIZE];
DWORD bytes_read;
HANDLE stdin_handle;
BOOL continue_reading;
unsigned int required_size;
bool read_successful = true;
stdin_handle = GetStdHandle(STD_INPUT_HANDLE);
if (stdin_handle == INVALID_HANDLE_VALUE) {
std::cout << "Error: invalid handle value!\n\n";
} else {
continue_reading = true;
while (continue_reading) {
continue_reading = ReadFile(stdin_handle, char_buffer, BUFSIZE,
&bytes_read, NULL);
if (continue_reading) {
if (bytes_read != 0) {
// Output what we have read so far
for (unsigned int i = 0; i < bytes_read; i++) {
std::cout << char_buffer[i];
}
} else {
continue_reading = false;
}
}
}
}
return 0;
}
I know that my only option with anonymous pipes is to do a blocking read with ReadFile. If I understand correctly, in regard to how I am invoking it, ReadFile will continue to read from the buffer on STDIN until it detects an end of write operation on the other end of the pipe (perhapse reads some sort of "end of write" token??). I would like to know if there is some sort of "beginning write" token that will be in the buffer if something is being piped in which I can check on STDIN BEFORE I call ReadFile. If this were the case I could just skip calling ReadFile and use some default text.
If there is not a way to do this, I can always pass in a command line argument that denotes that I should not check the pipe and just use the default text (or the other way around), but I would much prefer to do it the way that I specified.
Look at PeekNamedPipe(). Despite its name, it works for both named and anonymous pipes.
int main(int argc, const char *argv[])
{
char char_buffer[BUFSIZE];
DWORD bytes_read;
DWORD bytes_avail;
DWORD dw;
HANDLE stdin_handle;
bool is_pipe;
stdin_handle = GetStdHandle(STD_INPUT_HANDLE);
is_pipe = !GetConsoleMode(stdin_handle, &dw);
if (stdin_handle == INVALID_HANDLE_VALUE) {
std::cout << "Error: invalid handle value!\n\n";
} else {
while (1) {
if (is_pipe) {
if (PeekNamedPipe(stdin_handle, NULL, 0, NULL, &bytes_avail, NULL)) {
if (bytes_avail == 0) {
Sleep(100);
continue;
}
}
}
if (!ReadFile(stdin_handle, char_buffer, min(bytes_avail, BUFSIZE), &bytes_read, NULL)) {
break;
}
if (bytes_read == 0) {
break;
}
// Output what we have read so far
for (unsigned int i = 0; i < bytes_read; i++) {
std::cout << char_buffer[i];
}
}
}
return 0;
}
It looks like what you're really trying to do here is to determine whether you've got console input (where you use default value) vs pipe input (where you use input from the pipe).
Suggest testing that directly instead of trying to check if there's input ready: the catch with trying to sniff whether there's data in the pipe is that if the source app is slow in generating output, your app might make an incorrect assumption just because there isn't input yet available. (It might also be possible that, due to typeahead, there's a user could have typed in characters that area ready to be read from console STDIN before your app gets around to checking if input is available.)
Also, keep in mind that it might be useful to allow your app to be used with file redirection, not just pipes - eg:
myapp.exe < some_input_file
The classic way to do this "interactive mode, vs used with redirected input" test on unix is using isatty(); and luckily there's an equivalent in the Windows CRT - see function _isatty(); or use GetFileType() checking for FILE_TYPE_CHAR on GetStdHandle(STD_INPUT_HANDLE) - or use say GetConsoleMode as Remy does, which will only succeed on a real console handle.
This also works without overlapped I/O while using a second thread, that does the synchronous ReadFile-call. Then the main thread waits an arbitrary amount of time and acts like above...
Hope this helps...

Printing out the name of the first entry in the imports table of a PE file

I am trying to print out the name of the first entry (which I suppose is user32.dll) in the imports table of a PE file, but the program terminates unexpectedly saying "cannot read memory", can someone please explain me why??
#include<iostream>
#include<Windows.h>
#include<stdio.h>
#include<WinNT.h>
int main()
{
HANDLE hFile,hFileMapping;
LPVOID lpFileBase;
LPVOID lp;
if((hFile = CreateFile(TEXT("c:\\linked list.exe"),GENERIC_READ,FILE_SHARE_READ,NULL,OPEN_EXISTING,FILE_ATTRIBUTE_NORMAL,0)) == INVALID_HANDLE_VALUE)
std::cout<<"unable to open";
if((hFileMapping = CreateFileMapping(hFile,NULL,PAGE_READONLY,0,0,NULL)) == 0)
{
CloseHandle(hFile);
std::cout<<"unable to open for mapping";
}
if((lpFileBase = MapViewOfFile(hFileMapping,FILE_MAP_READ,0,0,0))== 0)
{
CloseHandle(hFile);
CloseHandle(hFileMapping);
std::cout<<"couldn't map view of file";
}
PIMAGE_DOS_HEADER pimdh;
pimdh = (PIMAGE_DOS_HEADER)lpFileBase;
PIMAGE_NT_HEADERS pimnth;
pimnth = (PIMAGE_NT_HEADERS)((char *)pimdh + pimdh->e_lfanew);
PIMAGE_SECTION_HEADER pimsh;
pimsh = (PIMAGE_SECTION_HEADER)(pimnth + 1);
int i;
for(i = 0; i<pimnth->FileHeader.NumberOfSections; i++)
{
if(!strcmp((char *)pimsh->Name,".idata"))
{
char *p;
PIMAGE_IMPORT_DESCRIPTOR pimid;
pimid = (PIMAGE_IMPORT_DESCRIPTOR)(pimnth->OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_IMPORT].VirtualAddress + (char *)lpFileBase);
p = (char *)((char *)lpFileBase + pimid->Name);
printf("%s",p);
};
pimsh++;
}
}
You asked a similar question a couple of days ago and looking at your code you've read two-thirds of my answer.
The other third says that pimid->Name is not a file offset, it's a Relative Virtual Address (or RVA), which you need to convert to a file offset. That's why you're getting an error. To understand RVAs read the MSDN article. For sample code to do the conversion have a look at pedump, which is referenced in the article.

Customise NSLog so it shows less info

by default NSLog outputs a long string before the requested output,
e.g:
NSLog(#"Log message");
Outputs to the console:
2011-04-15 11:23:01.692 MyAppName[23160:903] Log message
I know I can add the filename and line number to the log, but how do I get rid of all the date, time and app name that appears before the message?
I find it really clutters the console in Xcode making it harder to find the information I'm after.
This is definitely the FIRST thing I do on a new project. NSLog(…) has diarrhea of the mouth. Here is a basic macro that lets you get some peace and quiet.. AND log basic objects without the annoying NSLog(#"%#", xYz); syntax (instead you just NSLog(xYz);).
#define NSLog(fmt...) NSShutUp(__PRETTY_FUNCTION__,fmt)
#define UTF8FMT(fmt,argL) \
[NSString.alloc initWithFormat:fmt arguments:argL].UTF8String
void NSShutUp(const char*func, id fmt, ...) {
if (![fmt isKindOfClass:NSString.class])
// it's not a string (aka. the formatter), so print it)
fprintf (stderr, "%s: %s\n", func,
[[NSString stringWithFormat:#"%#",fmt,nil]UTF8String]);
else { va_list argList; va_start (argList, fmt);
fprintf (stderr, "%s: %s\n", func, UTF8FMT(fmt,argList));
va_end (argList);
} }
/* SAMPLE RUN */
int main (void) { NSString *a; NSNumber *b; NSArray *c;
NSLog(a = #"Ahh, silence." );
NSLog(b = #(M_PI) );
NSLog(c = #[#"Arrays, baby!"] );
// Old syntax still works.
NSLog(#"%# * %# * %#",a,b,c);
return 0;
}
OUTPUT
int main(): Ahh, silence.
int main(): 3.141592653589793
int main(): (
"Arrays, baby!"
)
int main(): Ahh, silence. * 3.141592653589793 * (
"Arrays, baby!"
)
i would recommend that you start using a better alternatives to NSlog like SOSMAX or NSLogger.
Here is a bit overview of both of them
http://learning-ios.blogspot.com/2011/05/better-nslog-ing.html

Resources